find 与 index 的区别:如果 find 没找到数据那么会返回-1,如果 index 没找到指定的数据,那么程序就会崩溃。
举个例子:
my_str = "hello"
result = my_str.index("e")
print(result)
result = my_str.find("h")
print(result)
程序输出:
D:*****.py
1
0
Process finished with exit code 0
find 索引出错时:
my_str = "hello"
result = my_str.index("e")
print(result)
result = my_str.find("h")
print(result)
result = my_str.find("t")
print(result)
程序输出:
D:*****.py
1
0
-1
Process finished with exit code 0
index 索引出错时:
my_str = "hello"
result = my_str.index("e")
print(result)
result = my_str.find("h")
print(result)
result = my_str.index("s")
print(result)
result = my_str.find("t")
print(result)
程序输出:
D:******.py
Traceback (most recent call last):
1
File "***.py", line 15, in <module>
0
result = my_str.index("s")
ValueError: substring not found
Process finished with exit code 1
及最后面的 index 索引出错后,后面的 find 索引没有运行,程序直接崩溃。