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

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.

Leave a comment

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