Does Python have a string 'contains' substring method?


Question

I'm looking for a string.contains or string.indexof method in Python.

I want to do:

if not somestring.contains("blah"):
   continue
1
3603
5/26/2017 6:02:52 PM

Accepted Answer

You can use the in operator:

if "blah" not in somestring: 
    continue
5665
11/11/2015 11:30:17 PM

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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon