Program to check whether the string starts and ends with the same character or not

by | Dec 26, 2020 | Python Programs

Introduction

The task is check whether the strings start character and end character is same or not.

check whether the string starts and ends with the same character

Program

import re 
def check_str(ip_str):
    re_exp = r'^[a-z]$|^([a-z]).*\1$'
 
    if(re.search(re_exp, ip_str)):   
        print("The input string {0} starts and ends with same character!".format(ip_str))   
    else:   
        print("The input string {0} does not starts and ends with same character!".format(ip_str))
        
ip_str = input("Enter the string: ")
check_str(ip_str)

Output

check whether the string starts and ends with the same character Output

Explanation

In the above python code, we have used regex expression r’^[a-z]$|^([a-z]).*\1$’. For single characters, the regex expression is r’^[a-z]$ and all the single characters satisfies the given condition. For multiple characters the regex expression is ^([a-z]).*\1$’. We have combined both the expressions in our code and used re.search() function to get the desired result.

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.