Python - Check whether a string starts and ends with the same character or not


When it is required to check if a string begins and ends with the same character or not, regular expression can be used. A method can be defined that uses the ‘search’ function to see if a string begins and ends with a specific character.

Example

Below is a demonstration of the same

import re

regex_expression = r'^[a-z]$|^([a-z]).*\1$'

def check_string(my_string):

   if(re.search(regex_expression, my_string)):
      print("The given string starts and ends with the same character")
   else:
      print("The given string doesnot start and end with the same character")

my_string = "abcbabda"

print("The string is:")
print(my_string)

check_string(my_string)

Output

The string is:
abcbabda
The given string starts and ends with the same character

Explanation

  • The required packages are imported.

  • A method named ‘check_string’ is defined that takes the string as a parameter.

  • The ‘search’ function is called by passing the string and the regular expression as parameters.

  • If the characters of the beginning and end match, 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.

Updated on: 20-Sep-2021

845 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements