Python Strings – Compare Nth Character

Python Strings – Compare Nth Character

You can compare the Nth character of two Python strings, by accessing the Nth 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 Nth character in given two strings, with a step by step process, and examples.

Steps to compare Nth character in the strings in Python

  1. Given two strings in x and y.
  2. Given position/index value on N in n.
  3. Get the Nth character in string x, using the expression x[n]. Please note that the index of characters in string start at 0. Therefore, in a string, it would be zeroth character, first character, second character, and so on.
    You may refer How to get character at specific index in Python string tutorial.
  4. Get the Nth character in string y, using the expression y[n].
  5. Compare the two characters using Equal-to comparison operator ==. The expression is x[n] == y[n]. This expression returns True if the Nth 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 Nth character in given two strings is given below.

Python Program

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

# Value of N
n = 3   # Fourth character

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

Output

The Nth characters are equal.

Explanation

P a p a y a
B a n a n a
      ↑
     n=3

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

Let us change the value of n to 2 run the program again.

Python Program

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

# Value of N
n = 2   # Fourth character

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

Output

The Nth characters are not equal.

Explanation

P a p a y a
B a n a n a
    ↑
   n=2

Since the Nth character from the given two strings x and y are "p" and "n" 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 Nth 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 👍