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.
1 2 3 4 5 | >>> >>> string1 = "Python is Awesome" >>> "is" in string1 True >>> |
Example 2: This example returns False as the original string does not contain the substring.
1 2 3 4 5 | >>> >>> string1 = "Python is Awesome" >>> "Hello" in string1 False >>> |

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
1 2 3 4 5 6 | >>> >>> string1 = "Programming is Love"; >>> string2 = "Love"; >>> string1.find(string2); 15 >>> |
Let us assume the string2 as the substring. Since the string1 variable contains the substring, the method returns 15.
Example 2
1 2 3 4 5 6 | >>> >>> string1 = "Programming is Love"; >>> string2 = "Hello"; >>> string1.find(string2); -1 >>> |
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
- Send Email with Python using SMTP
- Python Database Connection
- Range() Method in Python
- Python Sleep() Method
- Vernam Cipher Python Program