使用 Python 程序时,可能需要在另一个字符串中搜索并找到特定字符串。
这就是Python的内置字符串方法派上用场的地方。
在本文中,您将学习如何使用Python的内置字符串方法来帮助您搜索字符串中的子字符串。find()
以下是我们将涵盖的内容:
字符串方法内置于Python的标准库中。find()
它采用子字符串作为输入并查找其索引 - 即,子字符串在调用方法的字符串中的位置。
该方法的一般语法如下所示:find()
string_object.find("substring", start_index_number, end_index_number)
让我们分解一下:
该方法的返回值为整数值。find()
如果字符串中存在子字符串,则返回该给定字符串中指定子字符串的第一次出现的索引或字符位置。find()
如果要搜索的子字符串在字符串中不存在,则 将返回 。它不会引发异常。find()-1
下面的示例演示如何使用唯一必需的参数(要搜索的子字符串)来使用该方法。find()
您可以获取单个单词并进行搜索以查找特定字母的索引号:
fave_phrase = "Hello world!"# find the index of the letter 'w'search_fave_phrase = fave_phrase.find("w")print(search_fave_phrase)#output# 6
我创建了一个名为并存储字符串的变量。fave_phraseHello world!
我在包含字符串的变量上调用了该方法,并在里面搜索了字母“w”。find()Hello world!
我将操作结果存储在一个名为的变量中,然后将其内容输出到控制台。search_fave_phrase
返回值是索引,在本例中为整数 。w6
请记住,编程和计算机科学中的索引通常总是从 开始,而不是从 开始。01
将开始和结束参数与该方法结合使用可以限制搜索。find()
例如,如果要查找字母“w”的索引并从位置开始搜索,而不是更早开始搜索,则可以执行以下操作:3
fave_phrase = "Hello world!"# find the index of the letter 'w' starting from position 3search_fave_phrase = fave_phrase.find("w",3)print(search_fave_phrase)#output# 6
由于搜索从位置 3 开始,因此返回值将是包含该位置及以后的“w”的字符串的第一个实例。
您还可以进一步缩小搜索范围,并使用 end 参数更具体地进行搜索:
fave_phrase = "Hello world!"# find the index of the letter 'w' between the positions 3 and 8search_fave_phrase = fave_phrase.find("w",3,8)print(search_fave_phrase)#output# 6
如前所述,如果字符串中不存在您指定的子字符串,则输出将不存在,而不是异常。find()-1
fave_phrase = "Hello world!"# search for the index of the letter 'a' in "Hello world"search_fave_phrase = fave_phrase.find("a")print(search_fave_phrase)# -1
如果您在其他情况下搜索信件,会发生什么情况?
fave_phrase = "Hello world!"#search for the index of the letter 'W' capitalizedsearch_fave_phrase = fave_phrase.find("W")print(search_fave_phrase)#output# -1
在前面的示例中,我在短语“Hello world!”中搜索了字母的索引,该方法返回了其位置。wfind()
在这种情况下,搜索大写字母返回 - 这意味着字符串中不存在该字母。W-1
因此,在使用该方法搜索子字符串时,请记住,搜索将区分大小写。find()
使用关键字首先检查字符串中是否存在子字符串。in
关键字的一般语法如下:in
substring in string
关键字返回一个布尔值 , 该值可以是 或 。inTrueFalse
>>> "w" in "Hello world!"True
当字符串中存在子字符串时,运算符将返回。inTrue
如果子字符串不存在,则返回:False
>>> "a" in "Hello world!"False
在使用该方法之前,使用关键字是有用的第一步。infind()
首先检查字符串是否包含子字符串,然后可以使用 来查找子字符串的位置。这样,您就确信子字符串存在。find()
因此,用于查找字符串内子字符串的索引位置,而不是查找字符串中是否存在子字符串。find()
与该方法类似,该方法是用于查找字符串内子字符串索引的字符串方法。find()index()
因此,这两种方法的工作方式相同。
这两种方法之间的区别在于,当字符串中不存在子字符串时,该方法会引发异常,这与返回值的方法相反。index()find()-1
fave_phrase = "Hello world!"# search for the index of the letter 'a' in 'Hello world!'search_fave_phrase = fave_phrase.index("a")print(search_fave_phrase)#output# Traceback (most recent call last):# File "/Users/dionysialemonaki/python_article/demopython.py", line 4, in # search_fave_phrase = fave_phrase.index("a")# ValueError: substring not found
上面的示例显示,当子字符串不存在时,将引发 a。index()ValueError
当您不想处理程序中的任何异常时,您可能希望使用over。find()index()
留言与评论(共有 0 条评论) “” |