Open In App

Check if String Contains Substring in Python

This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. 

Input: Substring = "geeks" 
String="geeks for geeks"
Output: yes
Input: Substring = "geek"
String="geeks for geeks"
Output: yes
Explanation: In this, we are checking if the substring is present in a given string or not.

Python Substring in String

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:

Check Python Substring in String using the If-Else

In Python, you can check python substring in string is present using an if-else statement. The if-else statement allows you to conditionally execute different blocks of code based on whether the condition is true or false.




# Take input from users
MyString1 = "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")

Output

Yes! it is present in the string

Time Complexity : O(n)
Auxiliary Space : O(1)

Checking Python Substring in String using In Operator

In Python, you can easily check if a substring is present in a given string using the in operator. The in operator is used to test whether a particular value (substring) exists within a sequence.




text = "Geeks welcome to the Geek Kingdom!"
 
if "Geek" in text:
    print("Substring found!")
else:
    print("Substring not found!")
 
if "For" in text:
    print("Substring found!")
else:
    print("Substring not found!")

Output

Substring found!
Substring not found!

Time Complexity : O(n)
Auxiliary Space : O(1)

Checking Python Substring in String using Split() method

Checking python substring in string is present or not using split(). 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.




# input strings str1 and substr
string = "geeks for geeks"  # or string=input() -> taking input from the user
substring = "geeks"  # or substring=input()
 
# splitting words in a given string
s = string.split()
 
# checking condition
# if substring is present in the given string then it gives output as yes
if substring in s:
    print("yes")
else:
    print("no")

Output

Yes

Time Complexity : O(n + m)
Auxiliary Space : O(n)

Check Python Substring in String using 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. 




def check(string, sub_str):
    if (string.find(sub_str) == -1):
        print("NO")
    else:
        print("YES")
 
 
# driver code
string = "geeks for geeks"
sub_str = "geek"
check(string, sub_str)

Output

Yes

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String 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”.




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)

Output

No

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in string using Index() method

The Index() method returns the starting index of the substring passed as a parameter. Here “substring” is present at index 16.




any_string = "Geeks for Geeks substring "
start = 0
end = 1000
print(any_string.index('substring', start, end))

Output

16

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String using List Comprehension 

To check Python substring in string using list comprehension. Using list comprehension provides a concise way to check for a substring in a string and determine if it exists in any of the words.




s="geeks for geeks"
s2="geeks"
print(["yes" if s2 in s else "no"])

Output

['Yes']

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String using Lambda Function

To check Python substring in string using lambda function. Using a lambda function provides a concise way to check for a substring in a string and determine if it exists in any of the words.




s="geeks for geeks"
s2="geeks"
x=list(filter(lambda x: (s2 in s),s.split()))
print(["yes" if x else "no"])

Output

['Yes']

Time Complexity : O(n + m)
Auxiliary Space : O(m)

Check Python Substring in String using the “__contains__” magic class.

To check python substring in string we use __contains__(). This method is used to check if the string is present in the other string or not. 




a = ['Geeks-13', 'for-56', 'Geeks-78', 'xyz-46']
for i in a:
    if i.__contains__("Geeks"):
        print(f"Yes! {i} is containing.")

Output

Yes! Geeks-13 is containing.
Yes! Geeks-78 is containing.

Time Complexity : O(N)
Auxiliary Space : O(1)

Check Python Substring in String using Slicing 

Check python substring in string 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 otherwise returns False.




def is_substring(string, substring):
    for i in range(len(string) - len(substring) + 1):
        if string[i:i+len(substring)] == substring:
            return True
    return False
string = "A geeks in need is a geek indeed"
substring = "geeks"
print(is_substring(string,substring))

Output

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) 

Check Python Substring in String using Regular Expression

In Python, you can check python substring in string is present using regular expressions. Regular expressions provide powerful pattern matching capabilities, allowing you to define complex search patterns for substring matching. Here’s how you can use regular expressions to check for a substring in a string.




import re
 
MyString1 = "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")

Output

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

Check Python Substring in String using operator.contains() method

This Approach Used operator.contains() method to check whether the substring is present in string If the condition is True print yes otherwise print no




#Python program to check if a substring is present in a given string
import operator as op
s="geeks for geeks"
s2="geeks"
if(op.contains(s,s2)):
    print("yes")
else:
    print("no")

Output

Yes

Time Complexity : O(N)
Auxiliary Space : O(1) 


Article Tags :