Check if a string is in another string in Python
In this tutorial, we will learn various methods through which you can check whether a string is in another string in Python, also called a substring.
Using in operator
In this method, we will define two strings and check whether one string is present in another using the in
operator through the If-Else Statement.
string1 = "Hello, today is 5 Feb" string2 = "today is 5" if string2 in string1: print("Yes! It is present in the string") else: print("No! It is not present in the string")
Yes! It is present in the string
Note: This method also checks the order of the words. If the same order doesn’t exist, it will give you No.
Using find() method
The brute force approach you can think of is to run a for loop and check each word. For the same method, Python provides an inbuilt function called find()
which returns -1 if the substring is not found.
string = "Today is Monday" substring = "Mon" if string.find(substring) == -1: print("No! It is not present in the string") else: print("Yes! It is present in the string")
Yes! It is present in the string
Using count() method
You can also think of the solution as if the frequency of the substring is greater than 0 in the main string, then that means the substring is present. We can implement this thought process using the count()
method.
string = "2024 is a leap year" substring = "leap is" if string.count(substring) <0: print("No! It is not present in the string") else: print("Yes! It is present in the string")
Yes! It is present in the string
Using re
The regular expression (re) library provides many functions related to string manipulations. One such function is the search()
function, which can be implemented to check whether a string is the substring or not. Note the order in which the string variables are passed in the function. The string which we want to check is passed first.
import re s1 = "Today, it's raining outside." s2 = "rain" if re.search(s2, s1): print("Yes! it is present in the string") else: print("No! it is not present in the string")
Yes! it is present in the string
Leave a Reply