在Python中检查一个词是否存在于一个字符串中
假设存在一个字符串"The weather is so pleasant today"
。如果我们想检查这个字符串中是否有"weather"
,我们有多种方法可以查到。
在本指南中,我们将了解in
操作符、string.find()
方法、string.index()
方法和regular expression(RegEx)
。
在Python中使用in
操作符来检查一个词是否存在于一个字符串中
在字符串或序列(如列表、元组或数组)中搜索一个词的最简单方法之一是通过in
操作符。当在一个条件中使用时,它返回一个布尔值。
它可以是true
,也可以是false
。如果指定的词存在,语句的值是true
;如果该词不存在,它的值是false
。
这个运算符是case-sensitive
。如果我们试图在下面的代码中找到单词Fun
,我们将在输出中得到信息Fun not found
。
示例代码:
#Python 3.x
sentence = "Learning Python is fun"
word = "fun"
if word in sentence:
print(word, "found!")
else:
print(word, "not found!")
输出:
#Python 3.x
fun found!
如果我们想在一个字符串中检查一个词而不用担心大小写问题,我们必须将主字符串和要搜索的词转换为小写。在下面的代码中,我们将检查单词Fun
。
示例代码:
#Python 3.x
sentence = "Learning Python is fun"
word = "Fun"
if word.lower() in sentence.lower():
print(word, "found!")
else:
print(word, "not found!")
输出
#Python 3.x
Fun found!
在Python中使用String.find()
方法来检查一个词是否存在于一个字符串中
我们可以对一个字符串使用find()
方法来检查一个特定的词。如果指定的单词存在,它将返回该单词在主字符串中的left-most
或starting index
。
否则,它将简单地返回索引–1
。find()
方法还计算spaces
的索引。在下面的代码中,我们得到的输出是9
,因为9
是Python的起始索引,是字符P
的索引。
这个方法在默认情况下也是区分大小写的。如果我们检查单词python
,它将返回-1
。
示例代码:
#Python 3.x
string = "Learning Python is fun"
index=string.find("Python")
print(index)
输出:
#Python 3.x
9
使用String.index()
方法检查一个单词是否存在于Python的字符串中
index()
是与 方法相同的。这个方法同样返回主字符串中子串的最低索引。find()
唯一不同的是,当指定的词或子串不存在时,find()
方法返回索引-1,而index()
方法会引发一个异常(value error exception)
。
示例代码:
#Python 3.x
mystring = "Learning Python is fun"
print(mystring.index("Python"))
输出:
#Python 3.x
9
现在我们尝试找到一个在句子中不存在的词。
#Python 3.x
mystring = "Learning Python is fun"
print(mystring.index("Java"))
输出:
#Python 3.x
ValueError Traceback (most recent call last)
<ipython-input-12-544a99b6650a> in <module>()
1 mystring = "Learning Python is fun"
----> 2 print(mystring.index("Java"))
ValueError: substring not found
在Python中使用search()
方法来检查一个词是否存在于一个字符串中
我们可以通过search()
方法对字符串进行模式匹配来检查一个特定的词。这个方法在re
模块中可用。
这里的re
代表Regular Expression
。该搜索方法接受两个参数。
第一个参数是要找的词,第二个参数是整个字符串。但是这个方法的工作速度比其他方法慢。
示例代码:
#Python 3.x
from re import search
sentence = "Learning Python is fun"
word = "Python"
if search(word, sentence):
print(word, "found!")
else:
print(word, "not found!")
输出:
#Python 3.x
Python found!