str.find()
str.rfind()
【作用:類似index,查找字符】
【英語:r=》right|右邊,find=》尋找】
【說明:返回一個新的整數,查找到的位置,找不到出現-1,index找不到要報錯】
In [190]: "The stars are not afraid to appear like fireflies.".find("vition")#不存在返回-1 Out[190]: -1 In [192]: "The stars are not afraid to appear like fireflies.".find("a")#從左邊開始查找 Out[192]: 6 In [193]: "The stars are not afraid to appear like fireflies.".rfind("a")#從右邊開始查找 Out[193]: 32
str.count(sub[,start[,end]])
【作用:統計指定字符在字符串中出現的次數,可以根據起始和結束位置來統計】
【英語:count=>統計,case=》情況】
【說明:返回統計到的數量】
In [79]: "Man is a born child, his power is the power of growth. ".count("o")#從整個字符串中統計‘o’出現的次數 Out[79]: 5 In [80]: "Man is a born child, his power is the power of growth. ".count("o",0,11)#從位置0到11統計‘o’出現的次數 Out[80]: 1
str.index(sub[,start[,end]])
str.rindex(sub[,start[,end]])
【作用:從字符串左邊開始查找,sub=》要查找的子字符串,start=》開始的位置,從0開始,end=>結束的位置】
【英語:index=>索引,r=>right|右邊】
【說明:返回查找的字符串在源字符串的位置,找不到會報錯】
In [63]: "What you are you do not see".index("e")#默認從左邊開始查找, Out[63]: 11 In [43]: "What you are you do not see".rindex("e")#從右邊開始查找, Out[43]: 26 In [45]: "What you are you do not see".rindex("W",1)#從位置1開始並且從右邊開始查找 結果報錯 In [46]: "What you are you do not see".rindex("d",0,20))#從位置0到20中並且從右邊開始查找 Out[46]: 17