Python: Check if String Contains Substring
In this article, we’ll examine four ways to use Python to check whether a string contains a substring. Each has their own use-cases and pros/cons, some of which we’ll briefly cover here:
1) The in
Operator
The easiest way to check if a Python string contains a substring is to use the in
operator. The in
operator is used to check data structures for membership in Python. It returns a Boolean (either True
or False
) and can be used as follows:
fullstring = "StackAbuse"
substring = "tack"
if substring in fullstring:
print "Found!"
else:
print "Not found!"
This operator is shorthand for calling an object’s __contains__
method, and also works well for checking if an item exists in a list.
2) The String.index()
Method
The String type in Python has a method called index
that can be used to find the starting index of the first occurrence of a substring in a string. If the substring is not found, a ValueError
exception is thrown, which can to be handled with a try-except-else block:
fullstring = "StackAbuse"
substring = "tack"
try:
fullstring.index(substring)
except ValueError:
print "Not found!"
else:
print "Found!"
This method is useful