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

我想做的是:

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

当前回答

如果只是子字符串搜索,可以使用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”。类似地,如果s中的“is”将求值为True。这可能是你想要的,也可能不是你想要的。

其他回答

如果您对某个字符串中的“blah”感到满意,但希望它是一个函数/方法调用,那么您可能可以这样做

import operator

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

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

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

如果你真的需要一个方法而不是一个运算符(例如,为一个非常特殊的排序做一些奇怪的键…?),那就是“干草堆”__包含_。但是,既然你的例子是在if中使用的,我想你并不是真的想说什么;-)。直接使用特殊方法不是一种好的形式(既不可读,也不高效)——它们应该通过委托给它们的运算符和内置函数来使用。

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

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

使用in运算符:

if "blah" not in somestring: 
    continue

可以使用y.count()。

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

例如:

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