字元串方法
find join lower replace split strip translate
find:
可以在一個較長的字元串中查找字元串,傳回值是這個字元串所在的位置的最左端索引,找不到傳回 -1
例:
>>>‘With a moo-moo here,and a moo-moo there’.find('moo')
7
>>> ‘With a moo-moo here,and a moo-moo there’.find('hello')
-1
join:
連接配接序列中的元素,是 split 的逆方法
>>>sss = ['1','2','3'] #注意:這裡必須加引号,因為它隻能連接配接字元串
>>>ccc = '+'
>>>ccc.join(sss)
'1+2+3'
>>>dirs = '','usr','bin','env'
>>> '/'.join(dirs)
'/usr/bin/env'
>>> print 'C:' + '\\'.join(dirs)
C:\usr\bin\env
lower:
傳回字元中的小寫字母版
>>>‘Where Are You’.lower()
'where are you'
replace:
某字元串的所有比對項均被替換之後得到的字元串
例:
>>>'This is a test'.replace('is','eez')
'Theez eez a test'
split:
将字元串分割成序列,join方法的逆方法
>>>‘1+2+3+4’.split('+') #此處若不指定任何分割符,則以空格為分割符(空格,制表,換行等)
['1','2','3','4']
strip:
傳回去除兩側空格的字元串(不包括内部)
>>>‘ where are you ’.strip()
>>>'***where * are * you *********!'.strip(*!)
'where * are * you'
translate:
替換字元串中的某些部分,隻處理單個字元
本文轉自 tianshuai369 51CTO部落格,原文連結:http://blog.51cto.com/songqinglong/1712599