Check if String Contains a Substring in Python

The simplest way to check if a string contains a substring in Python is to use the in operator. This will return True or False depending on whether the substring is found. For example:

sentence = 'There are more trees on Earth than stars in the Milky Way galaxy'
word = 'galaxy'

if word in sentence:
    print('Word found.')

# Word found.

Case sensitivity

Note that the above example is case-sensitive so the words will need have the same casing in order to return True. If you want to do a case-insensitive search you can normalize strings using the lower() or upper() methods like this:

sentence = 'There are more trees on Earth than stars in the Milky Way galaxy'
word = 'milky'

if word in sentence.lower():
    print('Word found.')

# Word found.

Find index of a substring

To find the index of a substring within a string you can use the find() method. This will return the starting index value of the substring if it is found. If the substring is not found it will return -1.

sentence = 'There are more trees on Earth than stars in the Milky Way galaxy'

print(sentence.find('Earth'))
print(sentence.find('Moon'))

# 24
# -1

Count substrings

You can also count substrings within a string using the count() method, which will return the number of substring matches. For example:

sentence = 'There are more trees on Earth than stars in the Milky Way galaxy'
word = 'the'

print(sentence.lower().count(word))
# 2

Regex

For more advanced string searching you should consider reading up about Python's re module.


Horia Popa picture

Hi, how would you find the word if there was a period at the end? More generally, how would you separate the last word in a sentence from the punctuation, period, question or exclamation marks? Cheers!