Python是否有字符串包含子串的方法?

2024-04-24 19:46:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中寻找一个string.containsstring.indexof方法。

我想做:

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

Tags: 方法stringifnotblahcontainscontinuesomestring
10条回答

if needle in haystack:是正常的用法,正如@Michael所说——它依赖于^{}运算符,比方法调用可读性更强、速度更快。

如果你真的需要一个方法而不是一个运算符(例如,为一个非常特殊的排序做一些奇怪的key=…?),那就是^{}。但既然你的例子是在if中使用的,我想你说的不是真的;-)。直接使用特殊方法不是一种好的形式(既不可读,也不高效),而是通过委托给它们的运算符和内置函数来使用它们。

可以使用正则表达式获取引用:

>>> import re
>>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
['t', ' ', 't', ' ', ' ']

您可以使用y.count()

它将返回子字符串在字符串中出现次数的整数值。

例如:

string.count("bah") >> 0
string.count("Hello") >> 1

Does Python have a string contains substring method?

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

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

另一个(补语)则是原始问题所要求的not in

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

这在语义上与not 'foo' in '**foo**'相同,但它更具可读性,并在语言中显式地提供,以提高可读性。

避免使用__contains__findindex

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

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

返回True。也可以从超级字符串的实例调用此函数:

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

但不要。以下划线开头的方法在语义上被认为是私有的。使用它的唯一原因是在扩展innot 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'))),
}

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

如果您对"blah" in somestring很满意,但希望它是一个函数/方法调用,那么您可以这样做

import operator

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

Python中的所有操作符或多或少都可以在operator module中找到,包括in

你的答案是:

if "insert_char_or_string_here" in "insert_string_to_search_here":
    #DOSTUFF

用于检查是否为假:

if not "insert_char_or_string_here" in "insert_string_to_search_here":
    #DOSTUFF

或:

if "insert_char_or_string_here" not in "insert_string_to_search_here":
    #DOSTUFF

如果只是子字符串搜索,则可以使用string.find("substring")

不过,在使用^{}^{}^{}时,您确实需要小心一点,因为它们是子字符串搜索。换句话说,这:

s = "This be a string"
if s.find("is") == -1:
    print "No 'is' here!"
else:
    print "Found 'is' in the string."

它将类似地打印Found 'is' in the string.if "is" in s:将计算为True。这可能是你想要的,也可能不是。

inPython字符串和列表

以下是一些有用的例子,它们本身就说明了in方法:

"foo" in "foobar"
True

"foo" in "Foobar"
False

"foo" in "Foobar".lower()
True

"foo".capitalize() in "Foobar"
True

"foo" in ["bar", "foo", "foobar"]
True

"foo" in ["fo", "o", "foobar"]
False

警告。列表是iterable,in方法作用于iterable,而不仅仅是字符串。

您可以使用^{} operator

if "blah" not in somestring: 
    continue

很显然,在矢量比较中没有相似之处。一个显而易见的Python方法是:

names = ['bob', 'john', 'mike']
any(st in 'bob and john' for st in names) 
>> True

any(st in 'mary and jane' for st in names) 
>> False

相关问题 更多 >