The Wayback Machine - https://web.archive.org/web/20240930172631/https://www.geeksforgeeks.org/python-check-whether-a-string-starts-and-ends-with-the-same-character-or-not-using-regular-expression/
Open In App

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

Last Updated : 31 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Examples: 

Input :  
abba
Output :
Valid

Input :
a
Output :
Valid

Input :
abc
Output :
Invalid

Solution: 

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- 
'^[a-z]$'
  • 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-
'^([a-z]).*\1$'

The two regular expressions can be combined using |  

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

In this program, we will use search() method of re module.

Below is the implementation. 

Python3




# 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(re.search(regex, string)): 
        print("Valid") 
    else: 
        print("Invalid") 
 
if __name__ == '__main__' :
 
    sample1 = "abba"
    sample2 = "a"
    sample3 = "abcd"
 
    check(sample1)
    check(sample2)
    check(sample3)


Output : 

Valid
Valid
Invalid

Time Complexity : O(n), where n is length of string

Auxiliary Space : O(1)


Previous Article
Next Article

Similar Reads

Check if an URL is valid or not using Regular Expression
Given a URL as a character string str of size N.The task is to check if the given URL is valid or not.Examples : Input : str = "https://www.geeksforgeeks.org/" Output : Yes Explanation : The above URL is a valid URL.Input : str = "https:// www.geeksforgeeks.org/" Output : No Explanation : Note that there is a space after https://, hence the URL is
4 min read
How to check if a string starts with a substring using regex in Python?
Prerequisite: Regular Expression in Python Given a string str, the task is to check if a string starts with a given substring or not using regular expression in Python. Examples: Input: String: "geeks for geeks makes learning fun" Substring: "geeks" Output: True Input: String: "geeks for geeks makes learning fun" Substring: "makes" Output: FalseChe
3 min read
Find all the numbers in a string using regular expression in Python
Given a string str containing numbers and alphabets, the task is to find all the numbers in str using regular expression. Examples: Input: abcd11gdf15hnnn678hh4 Output: 11 15 678 4 Input: 1abcd133hhe0 Output: 1 133 0 Approach: The idea is to use Python re library to extract the sub-strings from the given string which match the pattern [0-9]+. This
1 min read
Check whether the Average Character of the String is present or not
Given a string of alphanumeric characters, the task is to check whether the average character of the string is present or not. Average character refers to the character corresponding to the ASCII value which is the floor of the average value of the ASCII values of all characters in the string. Examples: Input: abcdefOutput: d YesExplanation: string
7 min read
Python | Check if string ends with any string in given list
While working with strings, their prefixes and suffix play an important role in making any decision. For data manipulation tasks, we may need to sometimes, check if a string ends with any of the matching strings. Let's discuss certain ways in which this task can be performed. Method #1 : Using filter() + endswith() The combination of the above func
6 min read
Python - Check if string starts with any element in list
While working with strings, their prefixes and suffix play an important role in making any decision. Let’s discuss certain ways in which this task can be performed. Example: String = "GfG is best" Input_lis = ['best', 'GfG', 'good'] Output: True Explanation: 'GfG is best' is present in the list. String = "GfG is best" Input_lis = ['Good', 'Bad', 'N
4 min read
Python | Check whether two lists follow same pattern or not
Given two lists [Tex]A[/Tex] and [Tex]B[/Tex], check if they follow the same pattern or not. Condition for pattern matching: [Tex]Ai[/Tex] > [Tex]Aj[/Tex], then [Tex]Bi[/Tex] > [Tex]Bj[/Tex] [Tex]Ai[/Tex] = [Tex]Aj[/Tex], then [Tex]Bi[/Tex] = [Tex]Bj[/Tex] [Tex]Ai[/Tex] < [Tex]Aj[/Tex], then [Tex]Bi[/Tex] < [Tex]Bj[/Tex], for all i, j.
2 min read
Check if a column starts with given string in Pandas DataFrame?
In this program, we are trying to check whether the specified column in the given data frame starts with specified string or not. Let us try to understand this using an example suppose we have a dataset named student_id, date_of_joining, branch. Example: C/C++ Code #importing library pandas as pd import pandas as pd #creating data frame for student
2 min read
Validating Roman Numerals Using Regular expression
Given a String, and You have to validate whether the given String is Valid Roman Numeral or not. If it is valid print True else False.Note: Numerals are lying between 1 to 3999.Examples: Input: String = IX Output: True Input: String = 54IVC Output: False Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Roman numer
4 min read
Remove duplicate words from Sentence using Regular Expression
Given a string str which represents a sentence, the task is to remove the duplicate words from sentences using regular Expression in Programming Languages like C++, Java, C#, Python, etc. Examples of Remove Duplicate Words from SentencesInput: str = "Good bye bye world world" Output: Good bye world Explanation: We remove the second occurrence of by
5 min read
Open a File by Regular Expression in Python
Regular expressions (regex) are powerful tools for pattern matching and manipulation of text data. When it comes to opening files based on a specific pattern or criteria, regular expressions can be a handy solution. In this article, we will explore how to open a file using regular expressions in three different programming languages: Python, JavaSc
3 min read
How Can I Find All Matches to a Regular Expression in Python?
In Python, regular expressions (regex) are a powerful tool for finding patterns in text. Whether we're searching through logs, extracting specific data from a document, or performing complex string manipulations, Python's re module makes working with regular expressions straightforward. In this article, we will learn, how we can find all matches of
3 min read
Regular Expression (RegEx) in Python with Examples
A Regular Expression or RegEx is a special sequence of characters that uses a search pattern to find a string or set of strings. It can detect the presence or absence of a text by matching it with a particular pattern and also can split a pattern into one or more sub-patterns. Regex Module in PythonPython has a built-in module named "re" that is us
15+ min read
Check if a column ends with given string in Pandas DataFrame
In this program, we are trying to check whether the specified column in the given data frame ends with the specified string or not. Pandas endswith() is yet another method to search and filter text data in a DataFrame. This method is similar to Pandas.startwith() method. Syntax: string.endswith(value) Creating Dataframe to Check If a Column Ends wi
2 min read
Python Set | Check whether a given string is Heterogram or not
Given a string S of lowercase characters. The task is to check whether a given string is a Heterogram or not using Python. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Input1: S = "the big dwarf only jumps"Output1: YesExplanation: Each alphabet in the string S is occurred only once.Input2: S
3 min read
Python | Check whether string contains only numbers or not
Given a string, write a Python program to find whether a string contains only numbers or not. Let's see a few methods to solve the above task. Check if String Contains Only Numbers Check if String Contains Only Numbers using isdigit() method Python String isdigit() method returns “True” if all characters in the string are digits, Otherwise, It retu
4 min read
Python Program to check whether Characters of all string elements are in lexical order or not
Given a list with string elements, the task is to write a Python program to return True if all list elements are sorted. The point of caution here is to keep in mind we are comparing characters of a string list element with other characters of the same list element and not string elements with each other. Examples: Input : test_list = ["dent", "flo
4 min read
Python | Check whether a string is valid json or not
Given a Python String, the task is to check whether the String is a valid JSON object or not. Let's try to understand the problem using different examples in Python. Validate JSON String in PythonThere are various methods to Validate JSON schema in Python here we explain some generally used methods for validating JSON schema in Python which are the
3 min read
Regular Expression to Validate a Bitcoin Address
BITCOIN is a digital currency. During the digital currency transaction, a BTC address is required to verify the legality of a bitcoin wallet a Bitcoin address is a long set of alphanumeric characters that contains numbers and letters. A Bitcoin address indicates the source or destination of a Bitcoin payment. A Bitcoin wallet is a digital wallet th
6 min read
How to Return a Boolean Array True Where the String Array Ends with Suffix Using NumPy?
In this article, we will discuss how to return a boolean array that is True where the string element in the array ends with a suffix using NumPy in Python. Example: Check the array ends with Com Input: person_1@abc.com Output: True Input: person_3@xyz.co Output: False In Python, numpy.char module provides a set of vectorized string operations for a
2 min read
Return a boolean array which is True where the string element in array ends with suffix in Python
In this article, we are going to see how we will return a boolean array which is True where the string element in the array ends with a suffix in Python. numpy.char.endswith() numpy.char.endswith() return True if the elements end with the given substring otherwise it will return False. Syntax : np.char.endswith(input_numpy_array,'substring') Parame
2 min read
Python program to check whether the values of a dictionary are in same order as in a list
Given a dictionary, test if values are in order with list values. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub_list = [4, 10, 11] Output : True Explanation : Values are 4, 10, 11, same as list order. Hence True is returned. Input : test_dict = {"gfg" : 4, "is" : 10, "best" : 11}, sub_list = [4, 11, 10] Output : False Explanation : V
6 min read
How to check whether the day is a weekday or not using Pandas in Python?
Python is a very popular language because it is suitable for almost any type of data science task. And Pandas is one of the popular python-based data analysis toolkits and also provides pandas.bdate_range() function to return a fixed frequency DatetimeIndex. This function Returns a fixed frequency DatetimeIndex, with the business day(Mon to Fri) as
2 min read
Python - Test if all digits starts from % K digit
Sometimes we may face a problem in which we need to find for a list if it contains numbers which are % K. This particular utility has an application in day-day programming. Let’s discuss certain ways in which this task can be achieved. Method #1 : Using list comprehension + map() We can approach this problem by converting the elements to the string
5 min read
Python regex | Check whether the input is Floating point number or not
Prerequisite: Regular expression in Python Given an input, write a Python program to check whether the given Input is Floating point number or not. Examples: Input: 1.20 Output: Floating point number Input: -2.356 Output: Floating point number Input: 0.2 Output: Floating point number Input: -3 Output: Not a Floating point number In this program, we
2 min read
Python - Check whether the given List forms Contiguous Distinct Sub-Array or Not
You are given an array consisting of elements in the form A1, A2, A3.......An. The task is to find whether the array can be formed as a Contiguous Distinct Sub Array or Not. You need to find whether the array can be converted to contiguous sub-arrays that consist of similar elements and there are a distinct number of each element. The elements once
6 min read
Python PRAW – Check whether a redditor has Reddit premium or not
In Reddit, a redditor is the term given to a user. Reddit allows redditors to avail premium access by paying a fee. Here we will see how to check whether a redditor has the premium access or not. We will be using the is_gold attribute of the Redditor class to check whether a redditor has the premium access or not. Example 1 : Consider the following
2 min read
Check the equality of integer division and math.floor() of Regular division in Python
For large quotients, floor division (//) doesn't seem to be necessarily equal to the floor of regular division (math.floor(a/b)) Examples: Input : 269792703866060742 // 3 Output : 89930901288686914 Input : math.floor(269792703866060742 / 3) Output : 89930901288686912 In the above examples, the output for floor division(//) is 89930901288686914 and
2 min read
Check whether a number has consecutive 0's in the given base or not
Given a decimal number N, the task is to check if a number has consecutive zeroes or not after converting the number to its K-based notation. Examples: Input: N = 4, K = 2 Output: No 4 in base 2 is 100, As there are consecutive 2 thus the answer is No. Input: N = 15, K = 8 Output: Yes 15 in base 8 is 17, As there are no consecutive 0 so the answer
11 min read
Check whether a given column is present in a Pandas DataFrame or not
Consider a Dataframe with 4 columns : 'ConsumerId', 'CarName', CompanyName, and 'Price'. We have to determine whether a particular column is present in the DataFrame or not in Pandas Dataframe using Python. Creating a Dataframe to check if a column exists in Dataframe C/C++ Code # import pandas library import pandas as pd # dictionary d = {'Consume
2 min read