Signup/Sign In

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

In this tutorial, we will learn to check whether the string starts and ends with the same character or not.

The string is a sequence of one or more characters. So the regular expression can be used to check whether the string starts and ends with the same character.

Python Regex also called REs or regular expressions is a module using which we can specify rules to set the possible strings to match. It is available in re module.

Look at the examples to understand the input and output format.

Input: 'pop'

Output: valid input

Input: 'sort'

Output: invalid

To check whether the string starts and ends with the same character, we will use the following approach.

Use the regular expression to check the string starts with the same character.

For single-character use '^[a-z]$'.

For multiple-character use '^([a-z).*\1$' and combine both the expression using | .

Now use the re.search() method to match the regular expression with the input pattern.

Approach: Using search() method

In this method, we will match the first and last character within the input string using re.search() method.

Algorithm

Step1: Import re module

Step2: Define a regex expression for matching the first and last characters.

Step3: Use the regex method to match the pattern with the input string.

Step4: Print the output

Python Program 1

In this python program, we are searching for a valid pattern that has the same first and last characters.

# import module for regular expression 
import re
#input
string='pop'
#Expression to match first and last character
expression = r'^[a-z]$|^([a-z]).*\1$'
if(re.search(expression,string)):
  print("Valid input")
else:
  print("Invalid input")

Here is the output of the above code.


Valid input

Python Program 2

Here is another example to match the first and last character of the string.

# import module for regular expression 
import re
#input
string='sort'
#Expression to match first and last character
expression = r'^[a-z]$|^([a-z]).*\1$'
if(re.search(expression,string)):
  print("Valid input")
else:
  print("Invalid input")

Here is the output of the above code.


invalid input

Conclusion

In this tutorial, we have learned to check whether the first and last character of the given string matches or not. To do so, we have used python regex. It has been explained with examples.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.