Program to check whether the substring is present in the given string using Python

by | Mar 7, 2021 | Python Programs

Introduction

The task is to check whether the input string is present in our given phrase.

Program to check whether the substring is present in the given string

Program

import re


input_str = "Welcome to GoCoding! Have a happy learning!"
check_sub = input("Enter the string to check:")
# Using ''.find()
def check_sub_str(check_sub, input_str):
    if(input_str.find(check_sub) == -1):
        print("The given string is not the substring of '{0}' \n".format(input_str))
    else:
        print("YES, '{0}' is the substring of given string '{1}' \n".format(check_sub, input_str))
print("Output using ' '.find():")
check_sub_str(check_sub, input_str)


# Using re.search()
print("Output using regular expression:")
if re.search(check_sub, input_str):
    print("YES, '{0}' is the substring of given string '{1}' \n".format(check_sub, input_str))
else:
    print("The given string is not the substring of '{0}' \n".format(input_str))

 

Output

Program to check whether the substring is present in the given string Output

Explanation

In the above python code, we have used two ways to check the presence of substring. The first one is by using if condition. In python we have an in-built function ‘ ‘.find(). If the value returned by .find() is equalled to -1, then the searched string is not present in the given string else the string is present.

The second way is by regular expression. To use regular expression python has provided us the in-built package “re”. It will check for the input string pattern in the given phrase and return the specified value if found true.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.