Python 中查找函数:完整指南

了解如何使用Python中的find函数来搜索字符串中的子字符串。本文介绍 find 方法的语法、参数、返回值和示例。

Python String find() 方法的工作原理

Python 中的查找函数遵循简单的逻辑来搜索给定字符串中的子字符串。以下是该方法运作方式的关键方面:

  • find() 方法从字符串的开头(或选定的起始索引)开始搜索指定的子字符串。
  • 它检查字符串中的每个字符,看看它是否与子字符串的第一个字符匹配。
  • 如果找到匹配项,该方法将检查字符串和子字符串中的后续字符,直到验证整个子字符串。
  • 如果找到整个子字符串,该方法返回子字符串第一个字符的最低索引。如果没有找到子字符串,则返回-1。

Python String find() 方法的示例

a) find() 没有开始和结束参数

str = 'python is super easy to learn and work with'
print("found at: ", str.find('python'))
print(str.find('q'))

输出:

found at: 0
-1

在这里,我们创建了一个包含句子的变量 str,然后对 str 调用find() 并给出它 '& #39;并返回其在 str 中第一次出现的索引。python 将搜索 'find()'作为一个论点。因此,python

当未给出 startend 参数时,然后find()开始从头开始查找,直到字符串末尾。

str = 'I learned very early the difference between knowing the name of something and knowing something.'
print("found at: ", str.find('difference'))

输出:

found at:25

如果您未传递 startend<,则使用它们的默认值i=4> 参数。开始默认值为0,结束为字符串长度.

b) find() 带有 start 和 end 参数

str = 'Study hard what interests you the most in the most undisciplined, irreverent and original manner possible.'
print("found at: ", str.find('interests', 10, 30))
print("found at: ", str.find('interests', 30, 40))

输出

found at: 16
found at: -1

startend 参数设置范围并查找() 仅搜索该范围内的子字符串。

'兴趣'位于 第 16 位 位置,介于 10 到 30 之间,因此对于第一个 print(),输出为 16,第二个为 -1,因为'兴趣' 30 到 40 之间不存在。

Python String find() 方法的语法

string.find(substring, start, end)
  • string 是您要查找子字符串的原始句子/单词。

Python String find() 方法的参数

Python 中的 Find 函数具有可选参数,允许开发人员自定义搜索过程。以下是每个参数的解释:

  • 子字符串是您必须搜索的句子/单词。
  • 开始结束可选 参数。它们指定需要搜索子字符串的范围。

Python String find() 方法的返回值

  • 如果字符串中存在子字符串,则返回子字符串第一次出现的索引
  • 如果子字符串不存在,则返回-1

Python String find() 方法的异常

当然! Python 中的 Find 函数是一个强大的字符串操作工具,但了解潜在的异常情况至关重要。

  • 如果提供的开始或结束参数不是整数,则 find() 方法将引发 ValueError。
  • 另一个常见的异常是 TypeError,如果使用错误数量的参数调用 find() 方法,就会发生这种情况。
  • 如果对 None(表示不存在对象)的变量调用 find() 方法,则会导致 AttributeError。

#python 

Python 中查找函数:完整指南
1.40 GEEK