Python字符串是否有包含子字符串的方法

Python字符串是否有包含子字符串的方法

技术背景

在Python编程中,经常会遇到判断一个字符串是否包含另一个子字符串的需求。Python提供了多种方法来实现这一功能,不同方法在使用场景和性能上有所差异。

实现步骤

使用 in 操作符

in 操作符是Python中最常用的判断字符串包含关系的方法,它返回布尔值 TrueFalse,并且区分大小写。

1
2
if "blah" not in somestring:
continue

使用 str.find() 方法

str.find() 方法用于查找子字符串在字符串中的位置,如果找到则返回子字符串的起始索引,未找到则返回 -1。

1
2
3
4
5
s = "This be a string"
if s.find("is") == -1:
print("Not found")
else:
print("Found")

使用 str.index() 方法

str.index() 方法与 str.find() 类似,但当未找到子字符串时会抛出 ValueError 异常。

1
2
3
4
5
6
7
start = 100 
end = 1000
try:
any_string.index('substring', start, end)
print("Found")
except ValueError:
print("Not found")

使用 __contains__ 方法

__contains__ 方法实现了 in 操作符的底层逻辑,但不建议直接使用,因为以双下划线开头的方法通常是内部使用的。

1
str.__contains__('**foo**', 'foo')

使用 operator.contains() 函数

如果想将 in 操作符封装成函数调用,可以使用 operator.contains() 函数。

1
2
3
import operator
if not operator.contains(somestring, "blah"):
continue

使用 str.count() 方法

str.count() 方法可以返回子字符串在字符串中出现的次数,通过判断次数是否大于 0 来确定是否包含子字符串。

1
2
3
4
5
string = "Hello world"
if string.count("Hello") > 0:
print("Found")
else:
print("Not found")

使用正则表达式

使用 re 模块的 findall() 方法可以查找字符串中所有匹配的子字符串。

1
2
3
import re
to_search_in = "This is a test"
print(re.findall(r'( |t)', to_search_in)) # searches for t or space

核心代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 使用 in 操作符
if 'substring' in any_string:
print("Found")

# 使用 str.find() 方法
if any_string.find('substring') != -1:
print("Found")

# 使用 str.index() 方法
try:
any_string.index('substring')
print("Found")
except ValueError:
print("Not found")

# 使用 operator.contains() 函数
import operator
if operator.contains(any_string, 'substring'):
print("Found")

# 使用 str.count() 方法
if any_string.count('substring') > 0:
print("Found")

# 使用正则表达式
import re
if re.findall(r'substring', any_string):
print("Found")

最佳实践

  • 对于大多数情况,建议使用 in 操作符,因为它是Python语言设计的本意,代码更具可读性,并且性能最佳。
  • 如果需要知道子字符串的位置,可以使用 str.find()str.index() 方法。
  • 避免直接使用 __contains__ 方法,除非在实现或扩展 innot in 功能时。

常见问题

为什么 in 操作符比 __contains__ 方法更快?

通过 dis 模块反汇编代码可以发现,__contains__ 方法需要在Python虚拟机中单独查找和调用,而 in 操作符直接进行比较,因此 in 操作符更快。

1
2
3
from dis import dis
dis(lambda: 'a' in 'b')
dis(lambda: 'b'.__contains__('a'))

使用 str.find()str.index() 测试包含关系有什么问题?

使用 str.find()str.index() 测试包含关系时,需要额外处理返回值为 -1 或抛出 ValueError 异常的情况,并且如果子字符串在开头返回 0 时,布尔解释可能会产生误解。因此,在单纯判断包含关系时,建议使用 in 操作符。


Python字符串是否有包含子字符串的方法
https://119291.xyz/posts/2025-05-09.python-string-contains-substring-method/
作者
ww
发布于
2025年5月9日
许可协议