python 判断字符串是否包含关键字
方法 1:使用 in
关键字(最简洁)
直接通过 in
操作符检查子字符串是否存在:
text = "Hello, welcome to Python world."
keyword = "Python"
if keyword in text:
print(f"包含关键字 '{keyword}'")
else:
print(f"不包含关键字 '{keyword}'")
方法 2:使用 str.find()
方法
find()
返回子字符串的起始索引(未找到则返回 -1
):
text = "Hello, welcome to Python world."
keyword = "Python"
if text.find(keyword) != -1:
print("关键字存在")
else:
print("关键字不存在")
方法 3:使用 str.index()
方法
与 find()
类似,但未找到时会抛出 ValueError
异常:
try:
index = text.index(keyword)
print(f"关键字在索引 {index} 处")
except ValueError:
print("关键字不存在")
方法 4:正则表达式(复杂匹配)
使用 re
模块实现更灵活的匹配(如忽略大小写、模糊匹配等):
import re
text = "Hello, welcome to Python world."
pattern = r"python" # 正则表达式模式
if re.search(pattern, text, re.IGNORECASE): # 忽略大小写
print("关键字存在")
else:
print("关键字不存在")
扩展场景
1. 检查多个关键字是否存在
使用 any()
结合生成器表达式:
keywords = ["Python", "Java", "C++"]
text = "I love Python programming."
if any(k in text for k in keywords):
print("至少包含一个关键字")
2. 统计关键字出现的次数
使用 str.count()
:
count = text.count("Python")
print(f"关键字出现了 {count} 次")
总结
-
推荐使用
in
操作符:简单高效,适用于大多数场景。 -
正则表达式:适合需要模糊匹配(如大小写不敏感、模式匹配)的场景。
-
避免冗余代码:优先选择直接判断逻辑(如
if keyword in text
)。