API Navigator Logo

How to Compare Strings in Python

Author: Newtum

This guide explains the different ways to compare strings in Python, including equality checks and lexicographical (alphabetical) ordering.

Equality Comparison (`==` and `!=`)

You can check if two strings are exactly the same using the `==` operator, or if they are different using `!=`. This comparison is case-sensitive.

str1 = "python"
str2 = "Python"
str3 = "python"

print(f"'python' == 'Python' -> {str1 == str2}") # False
print(f"'python' == 'python' -> {str1 == str3}") # True
print(f"'python' != 'Python' -> {str1 != str2}") # True

Case-Insensitive Comparison

To compare strings regardless of their case, convert them both to the same case (e.g., lowercase or uppercase) before comparing.

str1 = "python"
str2 = "Python"

# Convert both to lowercase for comparison
is_equal_case_insensitive = str1.lower() == str2.lower()
print(f"Case-insensitive check: {is_equal_case_insensitive}")

Lexicographical Comparison (`<`, `>`, `<=`, `>=`)

You can also compare strings alphabetically. Python compares strings character by character based on their ASCII or Unicode values.

str_a = "apple"
str_b = "banana"

print(f"'apple' < 'banana' -> {str_a < str_b}") # True
print(f"'banana' < 'apple' -> {str_b < str_a}") # False
print(f"'A' < 'a' -> {'A' < 'a'}") # True, because uppercase letters have lower ASCII values