码迷,mamicode.com
首页 > 编程语言 > 详细

python字符串方法之查找

时间:2017-04-30 14:10:24      阅读:176      评论:0      收藏:0      [点我收藏+]

标签: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")#不存在返回-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

 

python字符串方法之查找

标签:text   span   默认   pytho   his   hit   字符串   logs   line   

原文地址:http://www.cnblogs.com/vition/p/6789241.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!