python中对字符串子串查找函数常用的有两个,分别为find()和index()
两者的作用都为可在字符串指定下标区间内查找子串所在的下标位置
str1 = "I like dogs"
print(str1.find("like", 0, 10))
# 2
str1 = "I like dogs"
print(str1.index("like", 0, 10))
# 2
由上述代码所示,两个函数都返回了原字符串中'like'中首字符下标
要注意,两个函数的作用仅为返回首个在字符串中匹配到的子串首字符下标
str1 = "I like dogs like"
print(str1.index("like", 0, 10))
# 2
由上述代码可见,第二个'like'并未被查找到,这时可以通过改变函数中指定查找范围的参数进行查找
str1 = "I like dogs like"
print(str1.index("like", 6, 20))
# 12
这里我将查找下标范围改为了6-20,成功匹配到第二个子串
find()和index()区别
两者区别为若查找失败,即未找到匹配的子串,find()会返回-1,而index()会报错
str1 = "I like dogs like"
print(str1.index("likeeee", 6, 20))
# Traceback (most recent call last):
# File "D:\Pythonproject\teach_day_01\demo01.py", line 2, in <module>
# print(str1.index("likeeee", 6, 20))
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# ValueError: substring not found
str1 = "I like dogs like"
print(str1.find("likeeee", 6, 20))
# -1