標籤:text span 預設 pytho his hit 字串 logs line
str.find()str.rfind()【作用:類似index,尋找字元】【英語:r=》right|右邊,find=》尋找】【說明:返回一個新的整數,尋找到的位置,找不到出現-1,index找不到要報錯】
In [190]: "The stars are not afraid to appear like fireflies.".find("vition")#不存在返回-1Out[190]: -1In [192]: "The stars are not afraid to appear like fireflies.".find("a")#從左邊開始尋找Out[192]: 6In [193]: "The stars are not afraid to appear like fireflies.".rfind("a")#從右邊開始尋找Out[193]: 32str.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]: 5In [80]: "Man is a born child, his power is the power of growth. ".count("o",0,11)#從位置0到11統計‘o’出現的次數Out[80]: 1str.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]: 11In [43]: "What you are you do not see".rindex("e")#從右邊開始尋找,Out[43]: 26In [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
python字串方法之尋找