5 Best Ways to Check if a Python String Starts and Ends With the Same Character

πŸ’‘ Problem Formulation: In Python, it’s common to need to verify whether the first and last character of a string are the same. This can be a part of data validation, parsing information, or formatting tasks. For example, given the input string "racecar", the desired output would be True because it starts and ends with the character ‘r’.

Method 1: Using String Indexing

This method involves directly accessing the first and last characters of the string using indexing. In Python, you can access characters in a string by their index, where the first character has index 0. By comparing the first and last character, you can determine if they are the same.

Here’s an example:

def check_same_char(s):
    return s[0] == s[-1]

print(check_same_char("racecar"))

Output: True

This code defines a function check_same_char that takes a string s and returns True if the first and last characters are the same by leveraging Python’s negative indexing to easily access the last character.

Method 2: Using the Ends with Method

Python’s str.endsWith() method can be repurposed to check if a string starts and ends with the same character by creating a substring of just the first character and passing it to the method.

Here’s an example:

def check_same_char(s):
    return s.endswith(s[0])

print(check_same_char("hello"))

Output: False

The function check_same_char takes a string s and uses the str.endswith() method to check if the string ends with the same character it starts with. In our example, “hello” does not start and end with the same character, hence the output is False.

Method 3: Using a Slice Operator

The slice operator in Python can be used to create new strings that are subsets of the original. By comparing a one-character slice of the first and last character, we can determine if a string starts and ends with the same character.

Here’s an example:

def check_same_char(s):
    return s[:1] == s[-1:]

print(check_same_char("banana"))

Output: False

Here, the check_same_char function compares slices of the string that represent the first and the last character. The slices s[:1] and s[-1:] will each return a one-character string, making it easy to compare them.

Method 4: Regular Expressions

Regular expressions are a powerful tool for text processing. By defining a pattern that describes a string starting and ending with any character and capturing that character for a backreference, we can use regular expressions to solve this problem.

Here’s an example:

import re

def check_same_char(s):
    return bool(re.match(r'^(.).*\1$', s))

print(check_same_char("abba"))

Output: True

The regular expression ^(.).*\1$ captures the first character with (.) and uses \1 to backreference this captured character at the end of the string. The function returns True if the pattern matches, indicating the string starts and ends with the same character.

Bonus One-Liner Method 5: Using Logical Operators

A one-liner solution leveraging logical operators can provide an elegant and concise way to check if a string starts and ends with the same character. This method is especially useful for inline checks and can be easily integrated into conditional statements.

Here’s an example:

print(("" and False) or "racecar"[0] == "racecar"[-1])

Output: True

The one-liner uses logical operators to check for an empty string edge case, returning False if the string is empty, or comparing the first and last character directly if it’s not.

Summary/Discussion

  • Method 1: String Indexing. Simple and direct. May lead to IndexError on empty strings.
  • Method 2: str.endswith() Method. Makes use of built-in string methods. Requires handling edge cases for empty strings.
  • Method 3: Using a Slice Operator. Intuitive slicing logic. Slightly less direct than indexing.
  • Method 4: Regular Expressions. Highly flexible for complex patterns. May be overkill for simple checks and harder to read.
  • Method 5: Logical Operators One-Liner. Concise, but the logic can be less immediately clear and may confuse beginners.