How to Compare Two Strings Alphabetically in Python
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
<text_a> < <text_b>
<text_a> > <text_b>
| Part | What 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
print("apple" < "banana")
print("apple" < "Banana")
print("10" < "9")

Step 2: Run It
uv run python compare_strings.py
True
False
True

"apple" < "banana"isTrue:acomes beforeb."apple" < "Banana"isFalse: every capital letter comes before every lowercase one.ord("B")printed66andord("a")printed97."10" < "9"isTrue: the first characters decide, and1comes before9. The text isn't read as numbers.
The command works unchanged in PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Comparing version numbers as text | "2.15.0" >= "2.9" printed False, because 1 comes before 9 | Compare the parts as numbers, or use a version type from your tools |
| Mixing capital and lowercase letters | "apple" < "Banana" was False | Compare 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
- Value comparisons — how strings and other types compare.
- ord() — a character's Unicode number.
- str.lower() — a lowercase copy of a string.
