How to check if a string contains a substring in Python?

Better Stack Team
Updated on January 26, 2023

There are multiple ways to check if a string contains a specific substring.

Using in keyword

You can use in keyword to check if a string contains a specific substring. The expression will return boolean value.

if 'Stack' in 'BetterStack':
    print('Found it!')
    print('Did not found it!')

The general syntax is the following:

if substring in string:
    # substring is in string
    # substring is not in string

Using the String.index

You can also use String.index method to find specific the index in the string where the substring starts.

string = 'BetterStack'
substring = 'Stack'

except ValueError:
    print('Not found!')
    print('Found it!')

Using the String.find

Also, you can use the find function from the String class. This function will return -1 if the substring is not present in the string.

string = 'BetterStack'
substring = 'Stack'

if string.find(substring) != -1:
    print('Found it!')
    print('Not found!')
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack