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.
Table of Contents
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
PythonCan’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)
PythonUsing 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)
PythonCheck 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)
PythonThis 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.
John is a professional software engineer who has been solving problems with code for 15+ years. He has experience with full stack web development, container orchestration, mobile development, DevOps, Windows and Linux kernel development, cybersecurity, and reverse engineering. In his spare time, he’s researching the potential business applications of AI.