Python 是否有字符串“包含”子字符串方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3437059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does Python have a string 'contains' substring method?
提问by Blankman
I'm looking for a string.containsor string.indexofmethod in Python.
我正在寻找Python 中的string.containsorstring.indexof方法。
I want to do:
我想要做:
if not somestring.contains("blah"):
continue
采纳答案by Michael Mrozek
回答by eldarerathis
If it's just a substring search you can use string.find("substring").
如果它只是一个子字符串搜索,您可以使用string.find("substring").
You do have to be a little careful with find, index, and inthough, as they are substring searches. In other words, this:
你必须与小心一点find,index和in虽然,因为它们是字符串搜索。换句话说,这:
s = "This be a string"
if s.find("is") == -1:
print("No 'is' here!")
else:
print("Found 'is' in the string.")
It would print Found 'is' in the string.Similarly, if "is" in s:would evaluate to True. This may or may not be what you want.
它将打印Found 'is' in the string.类似地,if "is" in s:将评估为True。这可能是也可能不是您想要的。
回答by Alex Martelli
if needle in haystack:is the normal use, as @Michael says -- it relies on the inoperator, more readable and faster than a method call.
if needle in haystack:是正常使用,正如@Michael 所说——它依赖于in操作符,比方法调用更具可读性和更快。
If you truly need a method instead of an operator (e.g. to do some weird key=for a very peculiar sort...?), that would be 'haystack'.__contains__. But since your example is for use in an if, I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.
如果你真的需要一个方法而不是一个运算符(例如,key=为一个非常奇特的排序做一些奇怪的事情......?),那就是'haystack'.__contains__. 但是由于您的示例用于if,我想您并不是真正的意思;-)。直接使用特殊方法不是一种好的形式(既不可读,也不高效)——它们应该通过委托给它们的运算符和内置函数来使用。
回答by Aaron Hall
Does Python have a string contains substring method?
Python 有字符串包含子字符串的方法吗?
Yes, but Python has a comparison operator that you should use instead, because the language intends its usage, and other programmers will expect you to use it. That keyword is in, which is used as a comparison operator:
是的,但是 Python 有一个比较运算符,您应该改用它,因为该语言打算使用它,而其他程序员会希望您使用它。该关键字 is in,用作比较运算符:
>>> 'foo' in '**foo**'
True
The opposite (complement), which the original question asks for, is not in:
原始问题要求的相反(补充)是not in:
>>> 'foo' not in '**foo**' # returns False
False
This is semantically the same as not 'foo' in '**foo**'but it's much more readable and explicitly provided for in the language as a readability improvement.
这在语义上是相同的,not 'foo' in '**foo**'但它更具可读性,并且作为可读性改进在语言中明确提供。
Avoid using __contains__, find, and index
避免使用__contains__, find, 和index
As promised, here's the containsmethod:
正如所承诺的,这是contains方法:
str.__contains__('**foo**', 'foo')
returns True. You could also call this function from the instance of the superstring:
返回True。您还可以从超字符串的实例中调用此函数:
'**foo**'.__contains__('foo')
But don't. Methods that start with underscores are considered semantically private. The only reason to use this is when extending the inand not infunctionality (e.g. if subclassing str):
但是不要。以下划线开头的方法在语义上被认为是私有的。使用它的唯一原因是在扩展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')
and now:
现在:
>>> 'substring' in ns
testing if "substring" in "a string with a substring inside"
True
Also, avoid the following string methods:
此外,避免使用以下字符串方法:
>>> '**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
Other languages may have no methods to directly test for substrings, and so you would have to use these types of methods, but with Python, it is much more efficient to use the incomparison operator.
其他语言可能没有直接测试子字符串的方法,因此您必须使用这些类型的方法,但是对于 Python,使用in比较运算符会更有效。
Performance comparisons
性能比较
We can compare various ways of accomplishing the same goal.
我们可以比较实现同一目标的各种方法。
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 inis 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}
回答by ytpillai
Here is your answer:
这是你的答案:
if "insert_char_or_string_here" in "insert_string_to_search_here":
#DOSTUFF
For checking if it is false:
要检查它是否为假:
if not "insert_char_or_string_here" in "insert_string_to_search_here":
#DOSTUFF
OR:
或者:
if "insert_char_or_string_here" not in "insert_string_to_search_here":
#DOSTUFF
回答by Ufos
So apparently there is nothing similar for vector-wise comparison. An obvious Python way to do so would be:
所以显然向量比较没有任何相似之处。一个明显的 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
回答by firelynx
inPython strings and lists
inPython 字符串和列表
Here are a few useful examples that speak for themselves concerning the inmethod:
以下是一些有用的示例,它们就该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
["foo" in a for a in ["fo", "o", "foobar"]]
[False, False, True]
Caveat. Lists are iterables, and the inmethod acts on iterables, not just strings.
警告。列表是可迭代对象,该in方法作用于可迭代对象,而不仅仅是字符串。
回答by Jeffrey04
If you are happy with "blah" in somestringbut want it to be a function/method call, you can probably do this
如果您"blah" in somestring对它感到满意但希望它是一个函数/方法调用,您可以这样做
import operator
if not operator.contains(somestring, "blah"):
continue
All operators in Python can be more or less found in the operator moduleincluding in.
Python 中的所有运算符或多或少都可以在运算符模块中找到,包括in.
回答by Muskovets
You can use regular expressions to get the occurrences:
您可以使用正则表达式来获取出现次数:
>>> import re
>>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
['t', ' ', 't', ' ', ' ']
回答by Brandon Bailey
You can use y.count().
您可以使用y.count().
It will return the integer value of the number of times a sub string appears in a string.
它将返回子字符串在字符串中出现的次数的整数值。
For example:
例如:
string.count("bah") >> 0
string.count("Hello") >> 1

