Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to check if a string starts with a substring using regex
When it is required to check if a string starts with a specific substring or not, with the help of regular expression, a method is defined that iterates through the string and uses the ‘search’ method to check if a string begins with a specific substring or not.
Example
Below is a demonstration of the same
import re
def check_string(my_string, sub_string) :
if (sub_string in my_string):
concat_string = "^" + sub_string
result = re.search(concat_string, my_string)
if result :
print("The string starts with the given substring")
else :
print("The string doesnot start with the given substring")
else :
print("It is not a substring")
my_string = "Python coding is fun to learn"
sub_string = "Python"
print("The string is :")
print(my_string)
print("The sub-string is :")
print(sub_string)
check_string(my_string, sub_string)
Output
The string is : Python coding is fun to learn The sub-string is : Python The string starts with the given substring
Explanation
The required packages are imported.
A method named ‘check_string’ is defined that takes the string and a substring as parameter.
It iterates through the string, and concatenates the ‘^’ with the substring.
This is assigned to a new variable.
The ‘search’ method is used to check for the substring in the new variable.
The result is assigned to a variable.
If this is result is a true value, relevant output is displayed on the console.
Outside the console, a string is defined, and is displayed on the console.
A substring is defined and is displayed on the console.
The method is called by passing the string and the substring.
The output is displayed on the console.