Does Python have a string 'contains' substring method?
I'm looking for a string.contains or string.indexof method in Python.
I want to do:
if not somestring.contains("blah"):
continue
您可以使用in运算符:
if "blah" not in somestring:
continue
If it's just a substring search you can use string.find("substring") .
You do have to be a little careful with find , index , and in though, as they are substring searches. In other words, this:
s = "This be a string"
if s.find("is") == -1:
print "No 'is' here!"
else:
print "Found 'is' in the string."
It would print Found 'is' in the string. Similarly, if "is" in s: would evaluate to True . This may or may not be what you want.
if needle in haystack: is the normal use, as @Michael says -- it relies on the in operator, more readable and faster than a method call.
If you truly need a method instead of an operator (eg to do some weird key= for a very peculiar sort...?), that would be 'haystack'.__contains__ . But since your example is for use in an if , I guess you don't really mean what you say;-). It's not good form (nor readable, nor efficient) to use special methods directly -- they're meant to be used, instead, through the operators and builtins that delegate to them.
上一篇: “超级”在Python中做什么?
