Python Strings – Compare Last Character

Python Strings – Compare Last Character

You can compare the last character of two Python strings, by accessing the last character using index, and then using the Equal-to comparison operator == to compare the characters.

In this tutorial, we will see how to compare the last character in given two strings, with a step by step process, and examples.

Steps to compare last character in the strings in Python

  1. Given two strings in x and y.
  2. Get the last character in string x, using the expression x[-1].
    You may refer How to get last character in Python string tutorial.
  3. Get the last character in string y, using the expression y[-1].
  4. Compare the two characters using Equal-to comparison operator ==. The expression is x[-1] == y[-1]. This expression returns True if the last character from the two strings x and y are equal, or False otherwise. You can use this expression as a condition in a Python if else statement.

Program

The complete program to compare the last character in given two strings is given below.

Python Program

# Given strings
x = "Apple"
y = "Pebble"

# Compare the last character
if x[-1] == y[-1]:
    print(f'The last characters are equal.')
else:
    print(f'The last characters are not equal.')
Run Code Copy

Output

The last characters are equal.

Since the last character from the given two strings x and y are "e" and "e" respectively, which are equal, the Equal-to comparison operator returns True, and the if-block executes.

Let us change the string values in x and y and run the program again.

Python Program

# Given strings
x = "Apple"
y = "Banana"

# Compare the last character
if x[-1] == y[-1]:
    print(f'The last characters are equal.')
else:
    print(f'The last characters are not equal.')
Run Code Copy

Output

The last characters are not equal

Since the last character from the given two strings x and y are "e" and "a" respectively, which are not equal, the Equal-to comparison operator returns False, and the else-block executes.

Summary

In this tutorial of Python string tutorials, we learned how to compare the last character from two given strings using Equal-to comparison operator, with step by step process and example programs.

Related Tutorials

Code copied to clipboard successfully 👍