使用Python中的contains()函数进行字符串匹配与搜索
发布时间:2023-12-15 18:34:46
在Python中,contains()函数用于判断一个字符串是否包含另一个字符串。它返回一个布尔值,如果被搜索的字符串包含在目标字符串中,则返回True,否则返回False。
下面是使用contains()函数的一些例子:
**例子1:**
sentence = "Hello, world!"
search_word = "world"
if sentence.contains(search_word):
print("字符串中包含搜索词")
else:
print("字符串中不包含搜索词")
输出结果:
字符串中包含搜索词
**例子2:**
sentence = "Python is a popular programming language"
search_word = "java"
if sentence.contains(search_word):
print("字符串中包含搜索词")
else:
print("字符串中不包含搜索词")
输出结果:
字符串中不包含搜索词
**例子3:**
sentence = "I love to code in Python"
search_word = "code"
if sentence.contains(search_word):
print("字符串中包含搜索词")
else:
print("字符串中不包含搜索词")
输出结果:
字符串中包含搜索词
**例子4:**
sentence = "Python is an interpreted, high-level, general-purpose programming language."
search_word = "Python"
if sentence.contains(search_word):
print("字符串中包含搜索词")
else:
print("字符串中不包含搜索词")
输出结果:
字符串中包含搜索词
**例子5:**
sentence = "The quick brown fox jumps over the lazy dog"
search_word = "fox"
if sentence.contains(search_word):
print("字符串中包含搜索词")
else:
print("字符串中不包含搜索词")
输出结果:
字符串中包含搜索词
使用contains()函数必须注意的两个要点是:
1. contains()函数只能用于字符串之间的匹配。
2. contains()函数是大小写敏感的,所以要确保大小写一致才能得到正确的结果。
综上所述,contains()函数是一种用于字符串匹配与搜索的实用工具,在编写Python程序时经常用到。
