Python中find()和index()的区别
在Python中,可以通过 Python 的内置函数使用 find() 或 index() 来查找字符串的索引。如果存在,它们都返回字符串中子字符串的起始索引。本文讨论了何时以及为什么使用哪一个。
index()函数
index() 方法返回字符串中子字符串或字符的索引(如果找到)。如果未找到子字符串或字符,则会引发异常。
句法:
string.index()
例子:
Python3
string = 'geeks for geeks'
# returns index value
result = string.index('for')
print("Substring for:", result)
result3 = string.index("best")
print("substring best:", result3)
Python3
string = 'geeks for geeks'
# returns index value
result = string.find('for')
print("Substring for:", result)
result = string.find('best')
print("Substring best:", result)
输出:
Substring for: 6
Traceback (most recent call last):
File “
ValueError: substring not found
find() 方法
find() 方法返回子字符串或字符(如果找到)第一次出现的索引。如果未找到,则返回 -1。
句法:
string.find()
例子:
蟒蛇3
string = 'geeks for geeks'
# returns index value
result = string.find('for')
print("Substring for:", result)
result = string.find('best')
print("Substring best:", result)
输出:
Substring for: 6
Substring best: -1
index() 与 find() 之间的差异表
index() | find() |
---|---|
Returns an exception if substring isn’t found | Returns -1 if substring isn’t found |
It shouldn’t be used if you are not sure about the presence of the substring | It is the correct function to use when you are not sure about the presence of a substring |
This can be applied to strings, lists and tuples | This can only be applied to strings |
It cannot be used with conditional statement | It can be used with conditional statement to execute a statement if a substring is found as well if it is not |