了解如何使用Python中的find函数来搜索字符串中的子字符串。本文介绍 find 方法的语法、参数、返回值和示例。
Python 中的查找函数遵循简单的逻辑来搜索给定字符串中的子字符串。以下是该方法运作方式的关键方面:
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
当未给出 start 和 end 参数时,然后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
如果您未传递 start 和 end<,则使用它们的默认值i=4> 参数。开始默认值为0,结束为字符串长度.
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
start 和 end 参数设置范围并查找() 仅搜索该范围内的子字符串。
'兴趣'位于 第 16 位 位置,介于 10 到 30 之间,因此对于第一个 print(),输出为 16,第二个为 -1,因为'兴趣' 30 到 40 之间不存在。
string.find(substring, start, end)
Python 中的 Find 函数具有可选参数,允许开发人员自定义搜索过程。以下是每个参数的解释:
当然! Python 中的 Find 函数是一个强大的字符串操作工具,但了解潜在的异常情况至关重要。