(007)我們一起學Python;元組和字串

雪山斐胡發表於2018-06-19

①元組的特徵是 圓括號和逗號   

 >>> tuple1=(1,)
    >>> type(tuple1)

    >>> type(tuple1)

    <class 'tuple'>


    >>> tuple1=(1,)
    >>> type(tuple1)

    <class 'tuple'>

②元組的內容不會被輕易修改:

    >>> tuple1 = (1,2,3,5,4,6,7,8)
    >>> tuple1[2]=(33,)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'tuple' object does not support item assignment


③修改元組的方法:元組被修改之後原來的會被回收,相當於標籤內容回收。

    >>> tuple1 = (1,2,3,5,4,6,7,8)
    >>> tuple1 = tuple1[2:] + (666,) + tuple1[:2]
    >>> tuple1
    (3, 5, 4, 6, 7, 8, 666, 1, 2)

④字串 str ,修改原內容也會回收

     >>> str = "tongge hen shuai!"
    >>> str1 = str[:2] + 'tebie' + str[2:]
    >>> str1
    'totebiengge hen shuai!'
    >>> str = str1
    >>> str

    'totebiengge hen shuai!'

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']


講解常用的幾個類方法:

①capitalize       :首字母大寫

    >>> str.capitalize()
    'Totebiengge hen shuai!'

②casefold         :整個字母改寫為小寫

    >>> str.casefold()
    'totebiengge hen shuai!'

③center            :字元居中

    >>> str.center(40)
    '         totebiengge hen shuai!         '

④count            :計數

    >>> str.count('g',1,15)
    2

⑤translate        :替換

    >>> str1.translate(str.maketrans('n','h'))

    'fish fuck ho ho ho '

二 格式化字串:位置引數,關鍵字引數,兩者混合引數

                                                              (位置引數必須在關鍵字引數之前)


    >>> "{a} {b} {c}".format(a="通哥",b="哥",c="很帥")
    '通哥 哥 很帥'


    >>> "{0} {1} {2}".format("通哥","很","帥")
    '通哥 很 帥'





相關文章