Python有没有字符串包含子串的方法?

3587 投票
10 回答
6721214 浏览
提问于 2025-04-16 02:30

我在找Python里有没有类似于 string.containsstring.indexof 这样的方法。

我想做的是:

if not somestring.contains("blah"):
   continue

10 个回答

523

Python有没有字符串包含子字符串的方法?

99%的使用场景可以用关键字 in 来解决,它会返回 True(真)或 False(假):

'substring' in any_string

如果你想获取子字符串的位置,可以使用 str.find(如果找不到会返回 -1,并且可以传入可选的位置参数):

start = 0
stop = len(any_string)
any_string.find('substring', start, stop)

或者使用 str.index(和 find 类似,但找不到时会抛出 ValueError 错误):

start = 100 
end = 1000
any_string.index('substring', start, end)

解释

使用 in 这个比较运算符是因为:

  1. 这是语言设计的初衷,
  2. 其他 Python 程序员也会期待你这样使用。
>>> 'foo' in '**foo**'
True

与原问题相反的情况是 not in

>>> 'foo' not in '**foo**' # returns False
False

这在语义上和 not 'foo' in '**foo**' 是一样的,但它更易读,并且在语言中明确提供了这种用法以提高可读性。

避免使用 __contains__

这个“包含”方法实现了 in 的行为。这个例子:

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

返回 True。你也可以从超字符串的实例中调用这个函数:

'**foo**'.__contains__('foo')

但不要这样做。以双下划线开头的方法被认为是语义上不公开的。使用这个方法的唯一理由是当你在实现或扩展 innot in 的功能时(例如,如果你在子类化 str):

class NoisyString(str):
    def __contains__(self, other):
        print(f'testing if "{other}" in "{self}"')
        return super(NoisyString, self).__contains__(other)

ns = NoisyString('a string with a substring inside')

现在:

>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True

不要用 findindex 来测试“包含”

不要用以下字符串方法来测试“包含”:

>>> '**foo**'.index('foo')
2
>>> '**foo**'.find('foo')
2

>>> '**oo**'.find('foo')
-1
>>> '**oo**'.index('foo')

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    '**oo**'.index('foo')
ValueError: substring not found

其他语言可能没有直接测试子字符串的方法,所以你可能需要使用这些方法,但在 Python 中,使用 in 比较运算符要高效得多。

而且,这些方法并不能直接替代 in。你可能需要处理异常或 -1 的情况,如果它们返回 0(因为找到了子字符串在开头),那么布尔值的解释是 False 而不是 True

如果你真的想表达 not any_string.startswith(substring),那就直接说。

性能比较

我们可以比较几种实现同样目标的方法。

import timeit

def in_(s, other):
    return other in s

def contains(s, other):
    return s.__contains__(other)

def find(s, other):
    return s.find(other) != -1

def index(s, other):
    try:
        s.index(other)
    except ValueError:
        return False
    else:
        return True



perf_dict = {
'in:True': min(timeit.repeat(lambda: in_('superstring', 'str'))),
'in:False': min(timeit.repeat(lambda: in_('superstring', 'not'))),
'__contains__:True': min(timeit.repeat(lambda: contains('superstring', 'str'))),
'__contains__:False': min(timeit.repeat(lambda: contains('superstring', 'not'))),
'find:True': min(timeit.repeat(lambda: find('superstring', 'str'))),
'find:False': min(timeit.repeat(lambda: find('superstring', 'not'))),
'index:True': min(timeit.repeat(lambda: index('superstring', 'str'))),
'index:False': min(timeit.repeat(lambda: index('superstring', 'not'))),
}

现在我们看到,使用 in 比其他方法快得多。用更少的时间完成相同的操作是更好的选择:

>>> perf_dict
{'in:True': 0.16450627865128808,
 'in:False': 0.1609668098178645,
 '__contains__:True': 0.24355481654697542,
 '__contains__:False': 0.24382793854783813,
 'find:True': 0.3067379407923454,
 'find:False': 0.29860888058124146,
 'index:True': 0.29647137792585454,
 'index:False': 0.5502287584545229}

如果 in 使用了 __contains__,那为什么 in 会比 __contains__ 更快?

这是一个很好的后续问题。

让我们拆解一下感兴趣的方法:

>>> from dis import dis
>>> dis(lambda: 'a' in 'b')
  1           0 LOAD_CONST               1 ('a')
              2 LOAD_CONST               2 ('b')
              4 COMPARE_OP               6 (in)
              6 RETURN_VALUE
>>> dis(lambda: 'b'.__contains__('a'))
  1           0 LOAD_CONST               1 ('b')
              2 LOAD_METHOD              0 (__contains__)
              4 LOAD_CONST               2 ('a')
              6 CALL_METHOD              1
              8 RETURN_VALUE

所以我们看到 .__contains__ 方法必须单独查找,然后从 Python 虚拟机中调用 - 这应该能很好地解释它们之间的差异。

908

如果你只是想查找一个子字符串,可以使用 string.find("substring")

不过在使用 findindexin 的时候要小心,因为它们都是用来查找子字符串的。换句话说,像这样:

s = "This be a string"
if s.find("is") == -1:
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")

它会输出 Found 'is' in the string. 同样,if "is" in s: 也会返回 True。这可能是你想要的,也可能不是。

8368

使用 in 操作符

if "blah" not in somestring: 
    continue

注意:这个操作是区分大小写的。

撰写回答