我正在寻找 Python 中的string.contains或string.indexof方法。
我想要做:
if not somestring.contains("blah"):
continue
您可以使用in运算符 :
if "blah" not in somestring:
continue
如果它只是一个子字符串搜索,你可以使用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.打印Found 'is' in the string.同样, if "is" in s:将评估为True 。这可能是也可能不是你想要的。
if needle in haystack:正常使用,正如 @Michael 所说 - 它依赖于in运算符,比方法调用更可读,更快。
如果你真的需要一个方法而不是一个操作符(例如做一些奇怪的key=非常奇怪的那种......?),那就是'haystack'.__contains__ 。但是因为你的例子是用于if ,我想你并不是真的意思是你说的;-)。直接使用特殊方法不是好形式(也不可读,也不高效) - 而是通过委托给它们的运算符和内置函数来使用它们。