Skip to content
Related Articles

Related Articles

Improve Article

Python – Check whether a string starts and ends with the same character or not (using Regular Expression)

  • Last Updated : 18 May, 2021
Geek Week

Given a string. The task is to write a regular expression to check whether a string starts and ends with the same character.

Input :  
Output :  

Input :  
Output :  

Input :  
Output :  

The input can be divide into 2 cases: 

  • Single character string: All single character strings satisfies the condition that they start and end with the same character. The regex for a string with only 1 character will be- 
  • Multiple character string: Here we need to check whether the first and the last character is same or not. We do this using \1. The regex will be- 

The two regular expressions can be combined using | 


In this program, we will use search() method of re module.
Below is the implementation.


# Python program to check if a string starts
# and ends with the same character
# import re module as it provides
# support for regular expressions
import re
# the regular  expression
regex = r'^[a-z]$|^([a-z]).*\1$'
# function for checking the string
def check(string):
    # pass the regular expression
    # and the string in the search() method
    if(, string)): 
if __name__ == '__main__' :
    sample1 = "abba"
    sample2 = "a"
    sample3 = "abcd"

Output : 



 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :