Comparing Strings: Equality and Ordering
Try it: Comparing Strings: Equality and Ordering
How Python compares two strings: == needs the same characters in the same order (capitalisation and spaces count), while <, >, <= and >= walk both strings from the left and let the first differing character decide by its code point — so every uppercase letter sorts before every lowercase one — with a prefix coming before the longer string, and .lower() on both sides making the comparison case-insensitive.
How it works
- == and != first compare lengths (different lengths are never equal), then the characters; case and spacing are part of the characters.
- <, <=, >, >= compare position 0 of both strings, then 1, 2, …; equal characters move on to the next position.
- The FIRST position whose characters differ decides, by their code points (ord): 'A'–'Z' are 65–90 and 'a'–'z' are 97–122, so 'Pineapple' < 'banana' and 'Z' < 'a'. Later characters are never looked at.
- If one string runs out first it is a prefix of the other, and the shorter string is smaller ('app' < 'apple'); with no difference at all the strings are equal.
- Calling .lower() on both strings before comparing makes capitalisation irrelevant (for equality and for ordering, e.g. sorted(words, key=str.lower)).
Default run (3 steps): Evaluate 'Pineapple' < 'banana'. Ordering compares the strings character by character, by code point (ord), from the left. … So 'Pineapple' < 'banana' is True. sorted([a, b]) would put 'Pineapple' first.
Simplified: Two strings of up to 16 characters (printable ASCII and a few Latin letters, all below U+0100, so code point and alphabet order are the same thing here). Results, .lower() and sorted() order match CPython 3.12 on 900+ random pairs.
Loading the simulation…