Python 如何检查字符串是否包含某个子串?
用 in 运算符:'sub' in text 返回布尔值;找位置用 str.find()(找不到返回 -1)或 str.index()(找不到抛异常)。本文给出用法与忽略大小写的写法。
最 Pythonic:if '子串' in 字符串:——in 运算符直接返回 True/False,可读性最好。
基本用法
text = "hello world"
'world' in text # True
'python' in text # False
if 'error' in log_line:
alert()
需要位置时
text.find('world') # 6(起始下标;找不到返回 -1)
text.index('world') # 6(找不到抛 ValueError)
text.count('o') # 2(出现次数)
忽略大小写
'ERROR' in log_line.lower() # 两边统一转小写再比
多个子串之一
if any(kw in text for kw in ['error', 'fail', 'exception']):
alert()
常见问题(FAQ)
Q:正则匹配怎么做? import re; re.search(r'err\w+', text)——返回 Match 对象或 None。
Q:in 的性能如何? 子串查找是优化过的(近似线性),日常文本完全够用;超大文本高频匹配考虑 re 预编译或专门索引。