python字符串方法之查找

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

 

posted @ 2017-04-30 12:43  老升尝谈  阅读(16506)  评论(0编辑  收藏  举报