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

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

题目

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

我想实现if not somestring.contains("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 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}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python 字符串 contains 方法是一个非常实用的字符串匹配方法,通常用于查询某个字符串是否包含另外一个字符串。这个方法可以用于所有字符串类型,包括普通的字符串和 Unicode 字符串。 在 Python 中,字符串类型是不可变的,所以我们不能直接修改字符串的内容。但是我们可以使用 contains 方法查询字符串是否包含某个子串。这个方法返回的是一个布尔类型值,如果包含子串则返回 True,否则返回 False。 contains 方法有两个参数,第一个参数是要查询的子串,第二个参数是可选的,表示匹配的起始位置。如果不指定第二个参数,则默认从字符串的开头开始匹配。 下面是一些使用 contains 方法的例子: s = "hello world" if "world" in s: print("s 包含 world 子串") if s.__contains__("world"): print("s 包含 world 子串") if s.find("world") != -1: print("s 包含 world 子串") 这些都是等价的语句,它们的输出都是 "s 包含 world 子串"。其中第一个例子使用了 in 关键字来判断字符串是否包含某个子串,第二个例子使用了字符串对象的 __contains__ 方法,而第三个例子则使用了 find 方法。 虽然它们的实现方式不同,但它们的作用都是相同的:查询字符串 s 是否包含 "world" 子串。如果包含,则输出提示信息。如果不包含,则什么也不做。 最后需要注意的是,contains 方法只会查询字符串是否包含某个子串,它并不会返回子串字符串中的位置。如果需要查询位置,需要使用其他方法,比如 find 或 index 方法。同时也需要注意编码问题,在处理 Unicode 字符串时,需要使用相应的编码方式来保证不出现乱码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值