Check if a String Contains Another String in Python

By | May 8, 2019

Let us learn how to check if a string contains another string in Python programming. There are multiple ways to search a substring, and let’s see them below.

Here, we’re going to talk about the 2 methods for searching algorithms in python programming specifically. If you’re a Java programmer, you may have used contains method to accomplish this functionality.

Method 1: Using the IN operator

The ‘in’ operator is one of the easiest methods to use to check whether a String contains substring or not.

The in operator helps to check whether a value exists in a sequence/string or not. It returns True if it finds the substring else returns False.

Example 1: This example returns True as the Substring is found.

Example 2: This example returns False as the original string does not contain the substring.

Check if a String contains another string using IN operator

Method 2: Using the find() method

The second method to find out if a string contains a substring or not is by using the find() method.

The find() method returns the index of the substring passed within the method arguments if the substring is found, else return -1 if the substring isn’t found.


The string find() method is one of the most popular ones as it allows the end user with more functionalities as compared to the IN operator.

Example 1


Let us assume the string2 as the substring. Since the string1 variable contains the substring, the method returns 15.

Example 2

Since the string2 is not present in the string1, the function returns -1.

If you have any doubts about how to check whether the string contains another string or not, let us know about it in the comment section.

Check out more algorithms on String searching on this Wikipedia page.

More Python Programs

Let's Discuss