Python | Check if a Substring is Present in a Given String
In this article, we will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check if a substring is there in the given string or not.
Example 1: Input : Substring = "geeks"
String="geeks for geeks"
Output : yes
Example 2: Input : Substring = "geek"
String="geeks for geeks"
Output : yesDoes Python have a string containing the substring method
Yes, Checking a substring is one of the most used tasks in python. Python uses many methods to check a string containing a substring like, find(), index(), count(), etc. The most efficient and fast method is by using an “in” operator which is used as a comparison operator. Here we will cover different approaches like:
- Using the if… in
- Checking using the split() method
- Using find() method
- Using “count()” method
- Using the index() method
- Using __contains__” magic class.
- Using regular expressions
Method 1: Check substring using the if… in.
Python3
# Take input from usersMyString1 = "A geek in need is a geek indeed"if "need" in MyString1: print("Yes! it is present in the string")else: print("No! it is not present") |
Yes! it is present in the string
Time Complexity : O(1)
Auxiliary Space : O(1)
Method 2: Checking substring using the split() method
Checking if a substring is present in the given string or not without using any inbuilt function. First split the given string into words and store them in a variable s then using the if condition, check if a substring is present in the given string or not.
Python3
# Python code# To check if a substring is present in a given string or not# input strings str1 and substrstring = "geeks for geeks" # or string=input() -> taking input from the usersubstring = "geeks" # or substring=input()# splitting words in a given strings = string.split()# checking condition# if substring is present in the given string then it gives output as yesif substring in s: print("yes")else: print("no") |
yes
Method 3: Check substring using the find() method
We can iteratively check for every word, but Python provides us an inbuilt function find() which checks if a substring is present in the string, which is done in one line. find() function returns -1 if it is not found, else it returns the first occurrence, so using this function this problem can be solved.
Python3
# function to check if small string is# there in big stringdef check(string, sub_str): if (string.find(sub_str) == -1): print("NO") else: print("YES")# driver codestring = "geeks for geeks"sub_str = "geek"check(string, sub_str) |
YES
Method 4: Check substring using “count()” method
You can also count the number of occurrences of a specific substring in a string, then you can use the Python count() method. If the substring is not found then “yes ” will print otherwise “no will be printed”.
Python3
def check(s2, s1): if (s2.count(s1) > 0): print("YES") else: print("NO")s2 = "A geek in need is a geek indeed"s1 = "geeks"check(s2, s1) |
NO
Method 5: Check substring using the index() method
The .index() method returns the starting index of the substring passed as a parameter. Here “substring” is present at index 16.
Python3
any_string = "Geeks for Geeks substring "start = 0end = 1000print(any_string.index('substring', start, end)) |
Output:
16
Method 6: Check substring using the “__contains__” magic class.
Python String __contains__(). This method is used to check if the string is present in the other string or not.
Python3
a = ['Geeks-13', 'for-56', 'Geeks-78', 'xyz-46']for i in a: if i.__contains__("Geeks"): print(f"Yes! {i} is containing.") |
Yes! Geeks-13 is containing. Yes! Geeks-78 is containing.
Method 7: Check substring using regular expressions
RegEx can be used to check if a string contains the specified search pattern. Python has a built-in package called re, which can be used to work with Regular Expressions.
Python3
# When you have imported the re module,# you can start using regular expressions.import re# Take input from usersMyString1 = "A geek in need is a geek indeed"MyString2 = "geeks"# re.search() returns a Match object# if there is a match anywhere in the stringif re.search(MyString2, MyString1): print("YES,string '{0}' is present in string '{1}'" .format( MyString2, MyString1))else: print("NO,string '{0}' is not present in string '{1}' " .format( MyString2, MyString1)) |
NO,string 'geeks' is not present in string 'A geek in need is a geek indeed'
Method: Using list comprehension
Python3
s="geeks for geeks"s2="geeks"print(["yes" if s2 in s else "no"]) |
['yes']
Method: Using lambda function
Python3
s="geeks for geeks"s2="geeks"x=list(filter(lambda x: (s2 in s),s.split()))print(["yes" if x else "no"]) |
['yes']
Method: Using countof function
Python3
import operator as ops="geeks for geeks"s2="geeks"print(["yes" if op.countOf(s.split(),s2)>0 else "no"]) |
['yes']
Method : Using operator.contains() method
Approach
- Used operator.contains() method to check whether the substring is present in string
- If the condition is True print yes otherwise print no
Python3
#Python program to check if a substring is present in a given stringimport operator as ops="geeks for geeks"s2="geeks"if(op.contains(s,s2)): print("yes")else: print("no") |
yes
Time Complexity : O(N)
Auxiliary Space : O(1)
Method: Using slicing
This implementation uses a loop to iterate through every possible starting index of the substring in the string, and then uses slicing to compare the current substring to the substring argument.
If the current substring matches the substring argument, then the function returns True. If the substring is not found after checking all possible starting indices, then the function returns False.
Python3
def is_substring(string, substring): for i in range(len(string) - len(substring) + 1): if string[i:i+len(substring)] == substring: return True return Falsestring = "A geeks in need is a geek indeed"substring = "geeks"print(is_substring(string,substring)) |
True
Time Complexity : O(n*m)
where n is the length of the string argument and m is the length of the substring argument. This is because the function uses a loop to iterate through every possible starting index of the substring in the string and then uses slicing to compare the current substring to the substring argument. In the worst case, the loop will iterate n-m+1 times, and each slice operation takes O(m) time, resulting in a total time complexity of O((n-m+1)m) = O(nm).
Auxiliary Space : O(1)
Using the re.search() function:
- Importing the regular expressions module in Python.
- Initializing a string variable with the given value.
- Checking if the word “need” is present in the string using the re.search() function.
- If the word “need” is present in the string, print “Yes! it is present in the string”.
- If the word “need” is not present in the string, execute the following block of code.
- If the word “need” is not present in the string, print “No! it is not present”.
Python3
import reMyString1 = "A geek in need is a geek indeed"if re.search("need", MyString1): print("Yes! it is present in the string")else: print("No! it is not present") |
Yes! it is present in the string
Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(1), as we are not using any additional space



Please Login to comment...