How to Check if a String Contains a Substring in Python
In Python, a substring is a contiguous sequence of characters within a string. There are several different ways to check whether a string contains a substring in Python, each suited for different situations.
Using the in Operator
The most simple way to check if a string contains a substring is to use the in
operator. We can write an if
statement to do something if the result returned from the in
condition is True
or False
.
string = 'We shall not cease from exploration'
substring = 'from'
if substring in string:
print(True)
else:
print(False)
True
Using the find() Method
The find()
method can be used to search for a substring in a string. It returns the index of the first character in the substring if a match is found. If no substring is found it will return -1
.
string = 'We shall not cease from exploration'
substring = 'from'
result = string.find(substring)
print(result)
19
string = 'We shall not cease from exploration'
substring = 'today'
result = string.find(substring)
print(result)
-1
Since we know find()
will return -1
if no substring has been found we can make a conditional if
statement to do something if the value returned is not -1
.
string = 'We shall not cease from exploration'
substring = 'today'
if string.find(substring) != -1:
print(True)
else:
print(False)
False
Find Substring After a Start Index
The find()
the method supports searching for a substring after a specific index. This is done by passing the number of the index as the second parameter.
string = 'We shall not cease from exploration'
substring = 'shall'
if string.find(substring, 10) != -1:
print(True)
else:
print(False)
False
Find Substring Before an End Index
To find substrings before an index, pass a third argument into find()
containing the last index to search.
string = 'We shall not cease from exploration'
substring = 'shall'
if string.find(substring, 0, 5) != -1:
print(True)
else:
print(False)
False
Using the index() Method
It is also possible to search for a substring using the index()
method. It works in a similar way to the find()
method except it will throw an error if the substring is not found. As a result, it will have to be wrapped in a try
except
block with an else
statement at the end to do something if a substring was found.
string = 'We shall not cease from exploration'
substring = 'food'
try:
string.index(substring)
except ValueError:
print(False)
else:
print(True)
False
note - like find()
, index()
also accepts a secondary start index and a tertiary end index argument.
Conclusion
You now know how to search for a substring in Python. The cleanest way to achieve this is with the in
operator but if you need more control the find()
method is better.