Answers:
您可以使用in运算符:
if "blah" not in somestring:
continue
TypeError: argument of type 'NoneType' is not iterable
in运算符是否使用Rabin-Carp算法?
如果只是子字符串搜索,则可以使用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.")
它将打印Found 'is' in the string.类似,if "is" in s:结果为True。这可能是您想要的,也可能不是。
if ' is ' in s:返回False。
\bis\b(单词边界)。
' is ',尤其是,它不会捕获This is, a comma'或捕获'It is.'。
s.split(string.punctuation + string.whitespace)拆分的实际输入会分裂一次;split是不是像strip/ rstrip/ lstrip家庭的功能,它只有当它看到所有的分隔符的,连续的,因为正确的顺序分割。如果要在字符类上拆分,则可以返回正则表达式(此时,r'\bis\b'不拆分即搜索是更简单,更快捷的方法)。
'is' not in (w.lower() for w in s.translate(string.maketrans(' ' * len(string.punctuation + string.whitespace), string.punctuation + string.whitespace)).split()-好的,点了。现在太荒谬了……
Python是否有包含子字符串方法的字符串?
是的,但是Python有一个比较运算符,您应该改用它,因为该语言打算使用它,而其他程序员则希望您使用它。该关键字是in,用作比较运算符:
>>> 'foo' in '**foo**'
True
原始问题要求的相反的(补码)是not in:
>>> 'foo' not in '**foo**' # returns False
False
这在语义上not 'foo' in '**foo**'与之相同,但是它在语言中更具可读性,并作为可读性的改进而明确提供。
__contains__,find和index如所承诺的,这是contains方法:
str.__contains__('**foo**', 'foo')
返回True。您也可以从超字符串的实例调用此函数:
'**foo**'.__contains__('foo')
但是不要。以下划线开头的方法在语义上被视为私有。使用此功能的唯一原因是在扩展inand 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 "<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}
str.index和str.find?您还建议别人如何找到子字符串的索引,而不仅仅是它是否存在?(或者您是说要避免使用它们代替包含-因此请不要使用它们s.find(ss) != -1代替ss in s?)
re模块可以更好地解决使用这些方法的意图。我尚未在我编写的任何代码中找到str.index或str.find自己的用途。
str.count(string.count(something) != 0)。颤抖
operator模块版本如何执行?
in_上面的相同-但周围有一个堆栈框架,因此它比那要慢:github.com/python/cpython/blob/3.7/Lib/operator.py#L153
if needle in haystack:正如@Michael所说,这是正常的用法-它依赖于in运算符,比方法调用更具可读性和速度。
如果您确实需要一个方法而不是一个运算符(例如,key=对一个非常特殊的类做一些奇怪的事情??),那就是'haystack'.__contains__。但是由于您的示例是用于的if,我想您并不是真的在说什么;-)。直接使用特殊方法不是很好的形式(既不可读也不高效),而是要通过委托给它们的运算符和内建函数使用它们。
in Python字符串和列表下面是一些有用的示例,它们说明了该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]
警告。列表是可迭代的,并且该in方法作用于可迭代的对象,而不仅仅是字符串。
["bar", "foo", "foobar"] in "foof"?
因此,显然,矢量方向比较没有类似之处。一个明显的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
in不应该与列表,因为它的元素的线性扫描使用,并缓慢进行比较。请改用一组,特别是如果要重复进行成员资格测试时。
您可以使用y.count()。
它将返回子字符串出现在字符串中的次数的整数值。
例如:
string.count("bah") >> 0
string.count("Hello") >> 1
__contains__(self, item),__iter__(self)和__getitem__(self, key)来确定项目是否位于给定的contains中。实现这些方法中的至少一种以使in您的自定义类型可用。