How to check if a string contains another string using Python.

Using find

find method returns the index of the substring in a string.

>>> "welcome to my world".find("my")
11

Using find you can check if a string contains another string or substring.

One gotcha with using the find method is it doesn’t know whether to look for the whole word or partial. For example,

>>> "there is a goal post".find("the")
0

You actually searched for the word the but the result was for the in there. So to search for the whole word you need to put space around the word.

>>> "there is a goal post".find(" the ")
8

Using In

If you don’t want the index, you can use the In method to check if a string contains another string.

>>> "the" in "there is the goal post"
True

This method also searches for the exact string and returns True or False based on the result.