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

Given two strings, check if s1 is there in s2.

Examples:

Input : s1 = geeks s2=geeks for geeks
Output : yes

Input : s1 = geek s2=geeks for geeks
Output : yes

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.
Method 1: Using user defined function.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:



YES          

Method 2: Using “count()” method:-

filter_none

edit
close

play_arrow

link
brightness_4
code

def check(s2, s1): 
    if (s2.count(s1)>0):     
        print("YES"
    else
        print("NO"
              
s2 = "A geek in need is a geek indeed"
s1 ="geek"
check(s2, s1) 

chevron_right


Output:

YES          

Method 3: 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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 ="geek"
  
# 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) )

chevron_right


Output:

YES,string 'geek' is present in string 'A geek in need is a geek indeed' 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Striver(underscore)79 at Codechef and codeforces D

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


8


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.