Program to check if a string starts with a substring or not using regex

by | Dec 26, 2020 | Python Programs

Home » Python » Python Programs » Program to check if a string starts with a substring or not using regex

Introduction

The task is to find whether the string starts with the given substring using regular expression.

check if a string starts with a substring

Program

import re 
def check(ip_str, substr): 
# Check string contains substring or not
    if (substr in ip_str): 
        pattern = "^" + substr 
# Check string starts with substring or not
        found = re.search( pattern, ip_str ) 
        if found : 
            return "The string starts with the given substring!" 
        else : 
            return "The substring is present in the given string but it doesn't start with the substring!" 
    else : 
        print("The substring is not present in the given string!")   
        
ip_str = input("Enter the string: ")
substr = "abc"
print(check(ip_str, substr))

Output

Output check if a string starts with a substring

Explanation

In the above python program firstly we have checked whether the substring is present in the given string. If the substring is present, we have used metacharacter “^” ( we can also use metacharacter “\A”) to check whether the string starts with the substring or not.

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.

Author