Python str.find() 方法用于返回子串第一次出现的位置,找不到返回 -1。
语法
s.find(sub, start=0, end=len(s))参数
sub:要查找的子串。可选 start/end:查找范围下标。
返回值
返回子串第一次出现的下标(整数);找不到返回 -1。
示例
s = "I love Python, Python is great"
print(s.find("Python")) # 7
print(s.find("python")) # -1,大小写敏感
print(s.find("Python", 10)) # 15,从下标10开始找
if s.find("Python") != -1:
print("包含 Python")输出:
7
-1
15
包含 Python注意事项
find 找不到返回 -1(不抛错);index 找不到抛 ValueError。想要最后一个位置用 rfind。