- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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.
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)
The string is: abcbabda The given string starts and ends with the same character
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.
- Related Articles
- Check whether the Average Character of the String is present or not in Python
- How to check whether a string starts with XYZ in Python?
- Count substrings that starts with character X and ends with character Y in C++
- Check whether a string is valid JSON or not in Python
- Check whether a character is Lowercase or not in Java
- Check whether a character is Uppercase or not in Java
- How to Check Whether a String is Palindrome or Not using Python?
- Python program to check whether a given string is Heterogram or not
- How to check if string or a substring of string ends with suffix in Python?
- How to check if string or a substring of string starts with substring in Python?
- Java Program to Check Whether a Character is Alphabet or Not
- Haskell Program to Check Whether a Character is Alphabet or Not