How to compare two strings in Python

Python comparison operators

To compare two strings, we mean that we want to identify whether the two strings are equivalent to each other or not, or perhaps which string should be greater or smaller than the other.

This is done using the following operators:

  • ==: This checks whether two strings are equal
  • !=: This checks if two strings are not equal
  • <: This checks if the string on its left is smaller than that on its right
  • <=: This checks if the string on its left is smaller than or equal to that on its right
  • >: This checks if the string on its left is greater than that on its right
  • >=: This checks if the string on its left is greater than or equal to that on its right

How to execute the comparison

String comparison in Python takes place character by character. That is, characters in the same positions are compared from both the strings.

If the characters fulfill the given comparison condition, it moves to the characters in the next position. Otherwise, it merely returns False.

Note: Some points to remember when using string comparison operators:

  • The comparisons are case-sensitive, hence same letters in different letter cases(upper/lower) will be treated as separate characters
  • If two characters are different, then their Unicode value is compared; the character with the smaller Unicode value is considered to be lower.

Example

Comparison is case-sensitive
1 of 5

Understanding the code

The code widget below uses the comparison operators that we have talked about above to compare different strings. Before we take a look at the code, below are the Unicode values for all the characters used in the code snippet:

  1. J - 0x004A
  2. j - 0x006A
  3. o - 0x006F
  4. h - 0x0068
  5. n - 0x006E
  6. D - 0x0044
  7. d - 0x0064
  8. e - 0x0065
name = 'John'
name2 = 'john'
name3 = 'doe'
name4 = 'Doe'
print("Are name and name 1 equal?")
print (name == name2)
print("Are name and name3 different?")
print (name != name3)
print("Is name less than or equal to name2?")
print (name <= name2)
print("Is name3 greater than or equal to name 2?")
print (name3 >= name2)
print("Is name4 less than name?")
print (name4 < name)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved