字符串索引
0 1 2 3 4
a p p l e
-5 -4 -3 -2 -1
for循環訪問字符
for c in s:
字符串切片
s.[begin:end]返回從索引begin到end-1的子串
測試函數
搜索函數
s.find(t) #找到返回t在s中的起始位置;否則返回-1
s.rfind(t) #與find相同,但從右往左搜索
s.index(t) #與find相同,但如果在s中找不到t則引發ValueError異常
s.rindex() #與index相同,但從右往左搜索
改變大小寫函數
設置格式函數
s.center(n,ch)
s.ljust(n,ch)
s.rjust(n,ch)
s.format(vars)
>>>'{0} likes {1}'.format('Jack','ice cream')
Jack likes ice cream
>>>'{who} {pet} has fleas '.format(pet = 'dog', who = 'my')
my dog has fleas
剝除函數
s.strip(ch) #從s開頭和末尾刪除所有在字符串ch中的字符
s.lstrip()
s.rstrip()
5.9拆分函數
s.partition(t) #將s拆分成三個字符串(head、t和tail)
s.rpartition(t) #與partition相同,但從s右端開始搜索
s.split(t) #以t爲分隔符,將s劃分成一系列子串,並返回一個由這些子串組成的列表
s.rsplit(t) #與split相同,但從s右端開始搜索t
s.splitlines() #返回一組由s中的各行組成的列表
替換函數
s.replace(old,new) #將s中的每個old替換成new
s.expandtabs(n) #將s中的每個製表符替換爲n個空格
其他函數
正則表達式
xy? --> x/xy
x|y --> x、y
x* --> ''、x、xx、xxx等
x+ --> x、xx、xxx等