The simplest way to check if a string contains a substring in Python is to use the
in operator. This will return
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:
# Word found.
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
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
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
For more advanced string searching you should consider reading up about Python's re module.