📜  Python中find()和index()的区别

📅  最后修改于: 2022-05-13 01:54:34.095000             🧑  作者: Mango

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)


输出:

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)

输出:

index() 与 find() 之间的差异表

index()find()
Returns an exception if substring isn’t foundReturns -1 if substring isn’t found
It shouldn’t be used if you are not sure about the presence of the substringIt 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 tuplesThis can only be applied to strings
It cannot be used with conditional statementIt can be used with conditional statement to execute a statement if a substring is found as well if it is not