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!')

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github