我正在寻找Python中的string.contains或string.indexof方法。
我想做的是:
if not somestring.contains("blah"):
continue
我正在寻找Python中的string.contains或string.indexof方法。
我想做的是:
if not somestring.contains("blah"):
continue
当前回答
if needle in haystack:这是正常的用法,正如@Michael所说——它依赖于in运算符,比方法调用更可读、更快。
如果你真的需要一个方法而不是一个运算符(例如,为一个非常特殊的排序做一些奇怪的键…?),那就是“干草堆”__包含_。但是,既然你的例子是在if中使用的,我想你并不是真的想说什么;-)。直接使用特殊方法不是一种好的形式(既不可读,也不高效)——它们应该通过委托给它们的运算符和内置函数来使用。
其他回答
if needle in haystack:这是正常的用法,正如@Michael所说——它依赖于in运算符,比方法调用更可读、更快。
如果你真的需要一个方法而不是一个运算符(例如,为一个非常特殊的排序做一些奇怪的键…?),那就是“干草堆”__包含_。但是,既然你的例子是在if中使用的,我想你并不是真的想说什么;-)。直接使用特殊方法不是一种好的形式(既不可读,也不高效)——它们应该通过委托给它们的运算符和内置函数来使用。
如果您对某个字符串中的“blah”感到满意,但希望它是一个函数/方法调用,那么您可能可以这样做
import operator
if not operator.contains(somestring, "blah"):
continue
Python中的所有运算符或多或少都可以在运算符模块中找到,包括中的。
您可以使用正则表达式获取引用:
>>> import re
>>> print(re.findall(r'( |t)', to_search_in)) # searches for t or space
['t', ' ', 't', ' ', ' ']
所以很明显,矢量比较没有类似的东西。一种明显的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
以下是您的答案:
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
OR:
if "insert_char_or_string_here" not in "insert_string_to_search_here":
#DOSTUFF