標籤:
基底字元串操作
所有標準的序列操作(索引、分區、乘法、判斷成員資格、求長度、取最大值和最小值),對字串同樣適用。但是,字串是不可改變的。
字串方法
字串的方法實在太多,這裡只介紹一些特別有用的。
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學習筆記(字串)