文章内容

2018/9/14 18:13:19,作 者: 黄兵

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

题目

我在Python中寻找判断 string.contains 或 string.indexof的方法

我想实现

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

链接

回答一

你可以使用 in 操作符

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 index

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

返回 True. 也可以通过字符串实例来调用这个方法

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

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

class 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 "<pyshell#40>", line 1, in <module>
    '**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 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'))),
}

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}

本文转载自:StackOverflow上票数最高的100个Python问题


分享到:

发表评论

评论列表