python學習筆記(字串)

來源:互聯網
上載者:User

標籤:

基底字元串操作

所有標準的序列操作(索引、分區、乘法、判斷成員資格、求長度、取最大值和最小值),對字串同樣適用。但是,字串是不可改變的。

字串方法

字串的方法實在太多,這裡只介紹一些特別有用的。

find

find方法可以在一個較長的字串中尋找子字串,它返回子字串所在位置的最左端索引。如果沒找到,則返回-1

>>> ‘With a moo-moo here. and a moo-moo there‘.find(‘moo‘)
7
>>> title="Monty Python‘s Flying Circus"
>>> title.find(‘Monty‘)
0
>>> title.find(‘Python‘)
6
>>> title.find(‘Flying‘)
15
>>> title.find(‘Zirquss‘)
-1

這個方法還可以接受可選的起始點和結束點參數。

>>> subject=‘$$$ Get rich now!!! $$$‘
>>> subject.find(‘$$$‘)
0
>>> subject.find(‘$$$‘,1)#只提供起始點
20
>>> subject.find(‘!!!‘)
16
>>> subject.find(‘!!!‘,0,16)#提供起始點和結束點
-1

join

join方法是非常重要的字串方法,它是split方法的逆方法,用來在隊列中添加元素

>>> seq=[‘1‘,‘2‘,‘3‘,‘4‘,‘5‘]
>>> sep=‘+‘
>>> sep.join(seq)
‘1+2+3+4+5‘
>>> dirs=‘‘,‘usr‘,‘bin‘,‘env‘
>>> ‘/‘.join(dirs)
‘/usr/bin/env‘
>>> print ‘C:‘+‘\\‘.join(dirs)
C:\usr\bin\env

lower

lower方法返回字串的小寫字母片

>>> ‘Trondheim Hammer Dance‘.lower()
‘trondheim hammer dance‘

如果想要編寫‘不區分大小寫’的代碼話,這個方法就派上用場了--代碼會忽略大小寫狀態
>>> name=‘Gumby‘
>>> names=[‘gumby‘,‘smith‘,‘jones‘]
>>> if name.lower() in names: print ‘found it!‘

found it!

replace

replace方法返回某字串的所有匹配項均被替換之後的得到字串

>>> ‘This is test‘.replace(‘is‘,‘eez‘)
‘Theez eez test‘

split

split是一個非常重要的方法,它是join的逆方法,用來將字串分割成序列。

>>> ‘1+2+3+4+5‘.split(‘+‘)
[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘]
>>> ‘/usr/bin/env‘.split(‘/‘)
[‘‘, ‘usr‘, ‘bin‘, ‘env‘]
>>> ‘Using the default‘.split()
[‘Using‘, ‘the‘, ‘default‘]

(如果不提供任何分隔字元,程式會把所有空格當成分隔字元)

strip

strip方法返回去除兩側(不包括內部)空格的字串

>>> ‘ internal whitespace is kept ‘.strip()
‘internal whitespace is kept‘
>>> ‘***SPAM*for*everyone!!!***‘.strip(‘*!‘)
‘SPAM*for*everyone‘

translate

translate和replace方法一樣,都可以替換字串中的某些部分,不同的是,translate只能替換單個字元

maketrans函數接受兩個參數:兩個等長的字串,表示第一個字串中的字元都用第二個字串中相同位置的字元替換

>>> from string import maketrans
>>> intab=‘aeiou‘
>>> outab=‘12345‘
>>> trantab=maketrans(intab,outab)
>>> str=‘this is string example....wow‘
>>> print str.translate(trantab)
th3s 3s str3ng 2x1mpl2....w4w

 

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.