Skip to content
Related Articles

Related Articles

Python | Check if a Substring is Present in a Given String

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 19 Sep, 2022
Improve Article
Save Article

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 : yes

Does 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:

Method 1: Check substring using the if… in.

Python3




# 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

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 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

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 string
 
 
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

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)

Output

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 = 0
end = 1000
print(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.")

Output

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 users
MyString1 = "A geek in need is a geek indeed"
MyString2 = "geeks"
 
# re.search() returns a Match object
# if there is a match anywhere in the string
if 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))

Output

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"])

Output

['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"])

Output

['yes']

Method: Using countof function 

Python3




import operator as op
s="geeks for geeks"
s2="geeks"
print(["yes" if op.countOf(s.split(),s2)>0 else "no"])

Output

['yes']

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!