python为字符串操作提供了很多常用的内建函数,让我们在操作字符串时能够更加简单方便。
下面以某个字符串为例来一一介绍一下
现有字符串:mystr = ‘hello world and hello python’
find(self, sub, start=None,end=None)
find 函数用于在给定的字符串中查找某个子字符串是否存在,如果找到则返回该子串的第一次出现的索引位置,否则返回-1
其中,self参数不用传递,sub就是要找的子字符串,start和end分别是字符串的开始和结束位置,如果不传递则默认从字符串的开始到字符串的结束位置。
使用方式:字符串.find(),比如查找python出现的位置
mystr = 'hello world and hello python'
#1.在整个字符串中查找
print(mystr.find('python'))
#输出结果
22
#2.在字符串的指定位置内查找
print(mystr.find('python',0,20))
#返回结果
-1
rfind(self, sub, start=None,end=None)
与find用法类似,只不过是从字符串的右侧开始查找,但索引依然是从左边计算
mystr = 'hello world and hello python'
#1.在整个字符串中查找
print(mystr.rfind('python'))
#输出结果
22
index(self,sub,start=None,end=None)
index函数与find函数的参数和用法一样,也是直接返回子串的索引位置。唯一不同的是当没有找到子串时不会返回-1而是直接报异常。示例代码:
mystr = 'hello world and hello python'
#1.在整个字符串中查找
print(mystr.index('python'))
#输出结果
22
#2.在字符串的指定位置内查找
print(mystr.index('python',0,20))
#返回结果
报异常:ValueError:substring not found
rindex(self,sub,start=None,end=None)
与index函数用法和功能一下,不同的是也是从字符串的右侧开始查找,但索引依然是从左侧计算
mystr = 'hello world and hello python'
#1.在整个字符串中查找
print(mystr.rindex('python'))
#输出结果
22
count(self,sub,start=None,end=None)
count函数用于