How to check if a string doesn’t contain a substring in Python

To check if a string doesn’t contain a substring in Python, just use the in operator. For example: "foo" not in "Hello world" will return True, i.e., the string “foo” isn’t found in the string “Hello world”. Alternatively, you can use the re library or the .rfind() method of Python’s built-in string class to do the same.

Check if a substring isn’t in a string using the in operator

This is the simplest and my preferred method of doing this:

mystring = "This is a test string"

print("Foo" in mystring)
# -> False
Python

Can’t get any simpler than that. It’s also the most readable. I’d chose this method if for no other reason than your teammates will thank you.

Check if a substring isn’t in a string using regex

If you want to get crazy, you can use the regex library re to do the same thing. Probably the easiest method in re to use is findall:

import re

mystring = "This is a test string"

print(len(re.findall("Foo", mystring)) != 0)
# -> False (string wasn't found)

print(len(re.findall("is", mystring)) != 0)
# -> True (string was found)
Python

Using re to do something as simple as this isn’t recommended as it’s kind of overkill. But, if you want to check if a particular pattern isn’t in the string, then it’s appropriate:

import re

mystring = "This is a test string"

print(len(re.findall(r"[0-9]+", mystring)) != 0)
# False (a substring of one or more numbers WASN'T found)
Python

Check if a substring isn’t in a string using .rfind()

The string class also has a built in method .rfind() which will find the index of the substring in the string it’s called on, or it’ll return -1 if it wasn’t found:

import re

mystring = "This is a test string"

print(mystring.rfind("foo") != -1)
# -> False (string wasn't found)
Python

This might be faster and a good idea if you are checking lots of strings in a tight loop. Otherwise, just use in.

Conclusion

You can use in, the re library, or .rfind() to see if a substring isn’t in a string in Python. I recommend using in unless you have a good reason to do otherwise, if for no other reason than it’s more readable.