Python Strings - Compare First Character


Python Strings - Compare First Character

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

Steps to compare first character in the strings in Python

  1. Given two strings in x and y.
  2. Get the first character in string x, using the expression x[0]. You may refer How to get first character in Python string tutorial.
  3. Get the first character in string y, using the expression y[0].
  4. Compare the two characters using Equal-to comparison operator ==. The expression is x[0] == y[0]. This expression returns True if the first 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 first characters in given two strings is given below.

Python Program

# Given strings
x = "Hello World!"
y = "Hello User!"

# Compare the first character
if x[0] == y[0]:
    print(f'The first characters are equal.')
else:
    print(f'The first characters are not equal.')

Output

The first characters are equal.

Since the first character from the given two strings x and y are "H" and "H" 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 = "Hello World!"
y = "Welcome!"

# Compare the first character
if x[0] == y[0]:
    print(f'The first characters are equal.')
else:
    print(f'The first characters are not equal.')

Output

The first characters are not equal

Since the first character from the given two strings x and y are "H" and "W" 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 first character from two given strings using Equal-to comparison operator, with step by step process and example programs.