Table of Contents
Introduction
The task is to find whether the string starts with the given substring using regular expression.
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
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.
0 Comments