substring在python中啥意思_Python有一个字符串'contains'substring方法吗?

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:05   6027   0

Python有一个字符串包含substring方法吗?

是的,但是Python有一个比较运算符,你应该使用它,因为语言意图使用它,而其他程序员会期望你使用它。 该关键字是in,用作比较运算符:

>>> 'foo' in '**foo**'

True

原始问题要求的相反(补语)是in:

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

False

这在语义上与in相同,但它在语言中作为可读性改进更具可读性和明确性。

避免使用in,not in和str

正如所承诺的,这是in方法:

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

返回in.您还可以从超级字符串的实例调用此函数:

'**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 "", 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 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}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875873
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP