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

我想做的是:

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

当前回答

以下是您的答案:

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

其他回答

使用in运算符:

if "blah" not in somestring: 
    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。这可能是你想要的,也可能不是你想要的。

在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方法作用于可迭代的对象,而不仅仅是字符串。

如果您想以更模糊的方式比较字符串以衡量它们的“相似性”,请考虑使用Levenshtein包

下面是一个说明其工作原理的答案。

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

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

以下是您的答案:

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