python contains_Python中有判断字符串包含(contains)子串的方法吗?

时间:2025-03-17 10:17:20

Python中有判断字符串包含(contains)子串的方法吗?

题目

我在Python中寻找判断 或 的方法

我想实现if not ("blah"):

continue

回答一if "blah" not in somestring:

continue

回答二Python中有字符串包含子串的方法吗?

是的,但是Python中有一个可使用的比较操作符,因为Python语言扩展它的用法,大部分程序员都会使用。这个操作符是 in。>>> 'foo' in '**foo**'

True

反过来,也是你问题中所问的,是 not in>>> 'foo' not in '**foo**' # returns False

False

语义上与 not 'foo' in 'foo'是一样的,但是可读性更好,是Python语言为改善可读性显式提供的。

避免使用 __contains__, find, and indexstr.__contains__('**foo**', 'foo')

返回 True. 也可以通过字符串实例来调用这个方法'**foo**'.__contains__('foo')

但是不要这么做,下划线开头的方法语义上被认为是私有方法,使用的唯一原因是当需要扩展in和 not in 的功能的时候,例如子类化strclass NoisyString(str):

def __contains__(self, other):

print('testing if "{0}" in "{1}"'.format(other, 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

而且,避免使用如下方法>>> '**foo**'.index('foo')

2

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

2

>>> '**oo**'.find('foo')

-1

>>> '**oo**'.index('foo')

Traceback (most recent call last):

File "", line 1, in

'**oo**'.index('foo')

ValueError: substring not found

其他语言可能没有方法直接去判断子串,所以你必须使用这几种方式,但是在Python中,用in操作符,性能会好得多。

性能比较

我们可以比较达到相同目的不同方法的性能import timeit

def in_(s, other):

return other in s

def contains(s, other):

return s.__contains__(other)

def find(s, other):

return (other) != -1

def index(s, other):

try:

(other)

except ValueError:

return False

else:

return True

perf_dict = {

'in:True': min((lambda: in_('superstring', 'str'))),

'in:False': min((lambda: in_('superstring', 'not'))),

'__contains__:True': min((lambda: contains('superstring', 'str'))),

'__contains__:False': min((lambda: contains('superstring', 'not'))),

'find:True': min((lambda: find('superstring', 'str'))),

'find:False': min((lambda: find('superstring', 'not'))),

'index:True': min((lambda: index('superstring', 'str'))),

'index:False': min((lambda: index('superstring', 'not'))),

}

And now we see that using in is much faster than the others. Less time to do an equivalent operation is better:

现在,我们可以看到使用 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}