python學習筆記——字串方法

來源:互聯網
上載者:User

標籤:字串固定操作

center:用來在兩邊填充字元,讓字串置中
‘the middle is sssssss‘.center(20)
‘ The middle is lx ‘

strip:刪除開頭結尾空白字元
‘ The middle is lx ‘.strip()
‘The middle is lx‘
names=[‘lx‘,‘dt‘,‘xx‘]

>> name=‘lx ‘
>> if name in names: print(‘this is true‘)
...
>> if name.strip() in names: print(‘this is true‘)
...
this is true

find:在字串中尋找子串,返回第一次出現子串的索引
‘The middle is lx‘.find(‘lx‘)
14

join:合并字串序列元素
seq=[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘]

>> sep.join(seq)
‘1+2+3+4+5‘

split:拆分字串序列
seq=‘1+2+3+4+5+6‘

>> seq().split(‘+‘)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ‘str‘ object is not callable
>> seq.split(‘+‘)
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘]
>> sep=seq.split(‘+‘)
>> sep
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘]

lower:返回字串小寫版本

‘TTT111‘.lower()
‘ttt111‘

replace:將指定字串替換為另一個字串。並返回替換後結果
this is a test‘.replace(‘is‘,‘are‘)
‘thare are a test‘

>> ‘this is a test‘.replace(‘is‘,‘ere‘)
‘there ere a test‘

translate:替換字串特定部分,只能單字元替換
要預先設定好轉換表,可採用str.maketrans(‘cs‘,‘kz‘)這種,maketrans接受兩個參數,兩個長度相同的字串,指定前一個字串被後一個字串替換,可以設定第三個參數為要刪除的指定字元,如空格
table=str.maketrans(‘cs‘,‘kz‘,‘‘)

>> ‘ffccctttsss sssssss‘.translate(table)
‘ffkkktttzzz zzzzzzz‘
>> ‘ffccctttsss sssssss‘.translate(table)
‘ffkkktttzzz zzzzzzz‘
>> table=str.maketrans(‘cs‘,‘kz‘,‘ ‘)
>> ‘ffccctttsss sssssss‘.translate(table)
‘ffkkktttzzzzzzzzzz‘

python學習筆記——字串方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.