1. find() 方法
语法
str.find(sub[, start[, end]])
参数
返回值
示例
text = "hello world"print(text.find("world")) # 输出 6print(text.find("Python")) # 输出 -1print(text.find("o", 5)) # 从索引5开始找"o",输出 7("world"中的'o')
特点
不会抛出异常,即使子串不存在也只是返回 -1,适合在不确定子串是否存在时使用。
大小写敏感,例如 "World" 和 "world" 是不同的。
只返回第一次出现的位置,若需查找所有出现位置,需结合循环。
2. index() 方法
语法
str.index(sub[, start[, end]])
参数
与 find() 完全相同。
返回值
找到子串时,返回第一次出现的起始索引。
找不到时,抛出 ValueError 异常。
text = "hello world"print(text.index("world")) # 输出 6# print(text.index("Python")) # 抛出 ValueError: substring not found
特点
3. 区别总结