Compare Text with casefold
Core idea
For Unicode-aware caseless comparison, casefold removes more case distinctions than lower. It can expand characters and is not a locale-specific sorting algorithm. For canonical caseless matching, normalize to NFD, casefold, then normalize to NFD again.
a, b = "Straße", "STRASSE"print(a.lower() == b.lower())print(a.casefold() == b.casefold())The sharp s expands to ss during case folding.
Build a comparison key
from unicodedata import normalizedef key(s): return normalize("NFD", normalize("NFD", s).casefold())print(key("É") == key("e\u0301"))Canonical decomposition handles the equivalent accents as well as case differences.
Common mistake
Do not replace stored names or identifiers with casefolded strings without a policy for collisions. Casefold is not accent removal or transliteration.
Practice
Build a separate search key for each label while preserving the original spelling. Try "Straße" and "STRASSE".
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Caseless comparison
Check your understanding of casefold and caseless matching.
What is printed?
print("ß".casefold())What is printed?
print("MASS".casefold() == "Maß".casefold())Does casefold remove all accents?
How should you use folded keys for search?