查找:
所谓字符串查找⽅法即是查找⼦串在字符串中的位置或出现的次数。
- find():检测某个⼦串是否包含在这个字符串中,如果在返回这个⼦串开始的位置下标,否则则返回-1。
语法:
字符串序列.find(⼦串, 开始位置下标, 结束位置下标)
注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。
学习代码如下:
mystr = "hello world and itcast and itheima and Python"
# 1、find()
# print(mystr.find('and')) # 12
# print(mystr.find('and',15,30)) # 23
# print(mystr.find('ands')) # -1 ands子串不存在
- index():检测某个⼦串是否包含在这个字符串中,如果在返回这个⼦串开始的位置下标,否则则报异常。
语法:
字符串序列.index(⼦串, 开始位置下标, 结束位置下标)
注意:开始和结束位置下标可以省略,表示在整个字符串序列中查找。
学习代码如下:
mystr = "hello world and itcast and itheima and Python"
# index()
# print(mystr.index('and')) # 12
# print(mystr.index('and',15,30)) #23
print(mystr.index ('ands')) # 如果index查找子串不存在,报错
- rfifind(): 和fifind()功能相同,但查找⽅向为右侧开始。
学习代码如下:
mystr = "hello world and itcast and itheima and Python"
# rfind()
# print(mystr.rfind('and')) # 35
# print(mystr.rfind('ands')) # -1
- rindex():和index()功能相同,但查找⽅向为右侧开始。
学习代码如下:
mystr = "hello world and itcast and itheima and Python"
# rindex
# print(mystr.rindex('and')) # 35
# print(mystr.rindex('ands')) # 报错
- count():返回某个⼦串在字符串中出现的次数
语法:
字符串序列.count(⼦串, 开始位置下标, 结束位置下标)
开始和结束位置下标可以省略,表示在整个字符串序列中查找。
学习代码如下:
mystr = "hello world and itcast and itheima and Python"
# count()
# print(mystr.count('and',15,30)) # 1
# print(mystr.count('and')) # 3
# print(mystr.count('ands')) # 0