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

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}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值