Skip to main content

How to Compare Two Strings Alphabetically in Python

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

Python can tell which of two pieces of text comes first, with the same < and > it uses for numbers. Its order is close to the alphabet, but not the same: capital letters and digits follow their own rules. This guide compares three pairs of strings on Python 3.15.2.

Syntax​

Syntax
<text_a> < <text_b>
<text_a> > <text_b>
PartWhat it means
<text_a>, <text_b>Two strings
<, >True when <text_a> comes before (<) or after (>) <text_b>. <= and >= work too

The Python reference says: "Strings (instances of str) compare lexicographically using the numerical Unicode code points (the result of the built-in function ord()) of their characters." Lexicographically means character by character from the left, like a dictionary: the first character that differs decides, by its number.

The Example​

Three comparisons: two lowercase words, the same words with one capital, and two numbers written as text.

Prerequisites​

  • uv and Python 3. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with uv init.

Step 1: Write the Script​

compare_strings.py
print("apple" < "banana")
print("apple" < "Banana")
print("10" < "9")

The compare_strings.py script in a macOS-style code window: print of "apple" < "banana", "apple" < "Banana" and "10" < "9".

Step 2: Run It​

Terminal
uv run python compare_strings.py
Output
True
False
True

The terminal after uv run python compare_strings.py: True, False, True.

  • "apple" < "banana" is True: a comes before b.
  • "apple" < "Banana" is False: every capital letter comes before every lowercase one. ord("B") printed 66 and ord("a") printed 97.
  • "10" < "9" is True: the first characters decide, and 1 comes before 9. The text isn't read as numbers.

The command works unchanged in PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Comparing version numbers as text"2.15.0" >= "2.9" printed False, because 1 comes before 9Compare the parts as numbers, or use a version type from your tools
Mixing capital and lowercase letters"apple" < "Banana" was FalseCompare lowercase copies: "apple".lower() < "Banana".lower() printed True

FAQ​

How does Python compare strings of different lengths?​

Character by character until one runs out: if all the characters so far are the same, the shorter string comes first. "app" < "apple" printed True.

What is ord()?​

A built-in function that gives a character's Unicode number, the number Python compares: ord("B") is 66, ord("a") is 97.

Conclusion​

"apple" < "banana" was True, "apple" < "Banana" was False because capitals come first, and "10" < "9" was True because text is compared character by character, not as numbers.

Additional Resources​