Python 是否有一个字符串 '包含'子串方法?

我正在寻找Python中的string.containsstring.indexof方法。

我想做的是

if not somestring.contains("blah"):
   continue
对该问题的评论 (1)
解决办法

你可以使用in运算符

if "blah" not in somestring: 
    continue
评论(14)

如果只是一个子串搜索,你可以使用string.find("substring")

你必须对find, index, 和in有点小心,因为它们是子串搜索。换句话说,这个。

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

它将打印在字符串中发现'is'。同样,if "is" in s:将评估为True。这可能是你想要的,也可能不是。

评论(8)

如果大海捞针:是正常的用法,正如@Michael所说--它依赖于in操作符,比方法调用更易读,更快。

如果你真的需要一个方法而不是一个运算符(例如,为一个非常奇特的排序做一些奇怪的key=?),那就是'haystack'.__contains__。 但由于你的例子是在if中使用的,我想你并不是真的想说什么;-)。) 直接使用特殊方法并不是好的形式(也不便于阅读,更没有效率)--它们应该通过委托给它们的操作符和内置程序来使用。

评论(0)

##Python 有一个字符串包含子串的方法吗?

是的,但是 Python 有一个比较操作符,你应该用它来代替,因为语言打算使用它,而且其他程序员会期望你使用它。 这个关键字是in,它被用作比较操作符。

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

原题所问的反义词(补语)是 "不在"。

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

这在语义上与 "not 'foo' in 'foo'`,但它的可读性更强,并且作为一种可读性改进在语言中明确规定。

避免使用__contains__findindex

说好的,这里是 "包含 "方法。

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

返回 "True"。 你也可以从superstring的实例中调用这个函数。

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

<!--

每个人都喜欢一个好的dataviz.这里有一个使用pandas和matplotlib的dataviz。 这里有一个使用pandas和matplotlib的。

import pandas
import matplotlib.pyplot as plt
s = pandas.Series(list(perf_dict.values()), index=list(perf_dict.keys()))
s.plot('bar')    
plt.show()

->

评论(5)

inPython字符串和列表

下面是几个有用的例子,关于 "进 "的方法,不言自明。

"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

注意事项。 列表是可迭代的,"in "方法对可迭代的东西起作用,而不仅仅是字符串。

评论(9)

所以显然,对于向量方面的比较,没有类似的方法。 一个显而易见的 Python 方法是:{{{7344992}}。

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
评论(2)

如果你对`"blah" 但希望它是一个函数/方法调用,你可以这样做。

import operator

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

在Python中所有的运算符都可以在[运算符模块][1]中或多或少的找到,包括in

[1]: https://docs.python.org/3.5/library/operator.html#operator.contains

评论(0)

你可以使用y.count()

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

例如:

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

string.count("bah") >> 0
string.count("Hello") >> 1
评论(10)

这是你的答案。

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
评论(0)

你可以使用正则表达式来获取出现次数。

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