Sub topic 7
Comparing and ordering strings
This chapter assumes you know that a string is a sequence of code points and that Python's str stores code points, not bytes. It also assumes you can read Big-O notation. Here you will learn how equality and ordering work, what they cost, and where they give surprising answers.
Equality: element by element
Two strings are equal when they have the same length and the same code point at every position. A comparison can stop early in two cases:
- The lengths differ. Many implementations check this first, because lengths are stored with the string.
- It reaches the first position where the code points differ.
If the strings are equal, or differ only at the end, the comparison must look at every character. So comparing two strings costs O(min(n, m)) in the worst case, not O(1). This matters when you compare long strings inside a loop.
One shortcut exists. If both names point to the same object in memory, equality is true without reading any characters. Interning (a later chapter) builds on this.
Lexicographic ordering
Ordering works like looking words up in a dictionary. You compare the first characters. If they differ, the smaller character decides the result. If they match, you move to the next position. If one string runs out first, the shorter string is smaller.
The following function implements this and checks it against Python's built-in operators:
def compare(a, b):
for x, y in zip(a, b):
if x != y:
return -1 if x < y else 1
if len(a) == len(b):
return 0
return -1 if len(a) < len(b) else 1
print(compare("apple", "apply")) # -1, because "e" < "y"
print(compare("app", "apple")) # -1, the prefix is smaller
print(compare("b", "apple")) # 1, because "b" > "a"
print(compare("same", "same")) # 0
print(("apple" < "apply") == (compare("apple", "apply") < 0)) # TrueThe cost is again O(min(n, m)). Sorting k strings takes O(k log k) comparisons, so the full cost is up to O(k log k × L), where L is the length of the longest common prefix between neighbors. Many strings with long shared prefixes, such as URLs or file paths, sort more slowly than the comparison count suggests.
What "smaller" means for a character
The comparison above relies on x < y for single characters. In Python this compares code points. Other languages compare the stored code units, and the encoding affects the result:
| Representation | Order of compared units |
|---|---|
| Python `str` | Code point order |
| UTF-8 bytes | Same as code point order |
| UTF-16 code units | Differs from code point order for characters above U+FFFF |
This is why a sort in one language can disagree with a sort in another for rare characters.
Code point order is not human order
Code point order ignores language and case. All uppercase ASCII letters come before all lowercase ones, and digits compare as characters, not as numbers.
words = ["banana", "Cherry", "apple"]
print(sorted(words)) # ['Cherry', 'apple', 'banana']
print(sorted(words, key=str.casefold)) # ['apple', 'banana', 'Cherry']
print("10" < "9") # True, because "1" < "9"
print(int("10") < int("9")) # Falsecasefold is a stronger form of lowercasing meant for comparison. For natural ordering of text in a given language, use a locale-aware tool such as locale.strxfrm or the ICU collation library. Use plain code point order when you only need a consistent, fast order, for example as the key order in a sorted index.
Equal-looking strings that are not equal
Strings that render the same can contain different code points. "café" written with one code point for é is not equal to "cafe" followed by a combining accent. Equality compares code points, not appearance. The chapter on grapheme clusters and normalization covers the fix. Normalize both sides to the same form before comparing text from different sources.
Comparison in practice
- Check
lenfirst if you only need to know whether two strings could be equal and lengths are cheap. - Compare hashes first when you compare the same strings many times. Equal strings always have equal hashes, so different hashes prove inequality in O(1) once the hashes are stored.
- Never use
<on numeric strings when you mean numeric order. Convert them first.
Exercise
Without running it, what does sorted(["b", "B", "a", "10", "9"]) return in Python, and why?
Show answer
['10', '9', 'B', 'a', 'b']. Python sorts by code point. The digits come first (code points 48 to 57), and "10" comes before "9" because "1" < "9". Next comes uppercase "B" (66), then lowercase "a" (97) and "b" (98).