How to Check String Contains Substring Python

Checking if a string contains a substring using Python

To check if a string contains a substring using Python, we can use one of following ways:

Using ‘in’ operator

Example:

> 'blah' in 'some string'
> False
> 'blah' in 'this string contains blah'
> True
Note
Under the hood, Python will use contains(self, item), iter(self), and getitem(self, key) in that order to determine whether an item lies in a given contains. Implement at least one of those methods to make in available to your custom type

Read more about in operator

Using ‘find’ function

s = "Python is awesome"
if s.find("Python") == -1:
    print('"Python" is not found')
else:
    print('"Python" is in the string')

Using ‘index’ function

s = "Python is awesome"
try:
    s.find("Python") == -1:
    print('"Python" is not found')
except ValueError:
    print('"Python" is in the string')
Note
The string.index() is like string.find(), but raise ValueError when the substring is not found.
Last modified October 4, 2020