Sub topic 3
Case: Lowercasing Versus Case Folding
This chapter assumes you can write basic Python (strings, functions, list comprehensions) and know that a Python str is a sequence of Unicode code points. The previous chapter covered code points, encodings, and what counts as a character. Here we use that to answer a narrower question: how should you make "Straße", "STRASSE", and "strasse" compare as equal?
Why case needs its own step
Case is the most visible surface variation in text. A search for "Python" should probably find "python", and a vocabulary that treats "The", "the", and "THE" as three words wastes counts and splits statistics.
The usual first answer is text.lower(). For English it works. Across other languages it fails in specific, predictable ways. Python offers a second method, str.casefold(), built for the comparison job that people often use lower() for.
Two different jobs
Unicode defines two kinds of case operation, and they answer different questions.
- Case mapping (
lower(),upper(),title()) produces text that reads correctly in a given case. The output is meant for people to look at. It follows the rules of writing: the Greek letter sigma, for example, has a different shape at the end of a word. - Case folding (
casefold()) produces a key for comparison. The output does not have to be good writing. It only has to be the same for any two strings that differ only by case.
A fold that is meant for matching can be more aggressive than a mapping meant for display. That is why the two methods disagree on some inputs.
The German sharp s
The letter ß is already lowercase. Its uppercase form is conventionally written "SS", so "Straße" and "STRASSE" are the same word in different case. Lowercasing does not make them match.
print("Stra\u00dfe".lower()) # straße
print("Stra\u00dfe".casefold()) # strasse
print("Stra\u00dfe".casefold() == "STRASSE".casefold()) # Truelower() leaves ß alone because it is already a lowercase letter. casefold() maps it to ss, which is also what "STRASSE" becomes. The string gets longer: one code point turned into two. That detail matters later.
What `lower()` and `casefold()` do differently
The two methods agree on ordinary letters. They differ on a small set of characters, and those characters are the reason the distinction exists.
| Input | `lower()` | `casefold()` | Why they differ |
|---|---|---|---|
| `ß` (U+00DF) | `ß` | `ss` | Folding expands the letter to match "SS". |
| `ς` (Greek final sigma) | `ς` | `σ` | Folding merges both sigma shapes. |
| `fi` (U+FB01, ligature) | `fi` | `fi` | Folding expands the ligature into two letters. |
| `İ` (U+0130, dotted capital I) | `i̇` (two code points) | `i̇` (two code points) | Both produce `i` plus a combining dot. |
| `A` | `a` | `a` | No difference for plain ASCII. |
Treat this table as a sample. The full list comes from the Unicode file CaseFolding.txt, and Python's casefold() implements it.
Greek sigma
Greek has two lowercase forms of sigma. The form σ appears inside a word and ς appears at the end. The capital is always Σ. Python's lower() is clever here: it picks the final form based on context.
word = "ΟΔΥΣΣΕΥΣ"
print(word.lower()) # οδυσσευς (final letter is ς)
print(word.casefold()) # οδυσσευσ (every sigma is σ)
typed = "οδυσσευς" # the same word, already lowercase
print(typed == word.lower()) # True
print(typed == word.casefold()) # False
print(typed.casefold() == word.casefold()) # TrueThe third-to-last line shows the trap. Comparing a casefolded string to an unfolded one fails, because folding changed the final ς into σ. Whenever you fold, fold both sides, or fold everything at the point where text enters your system.
The Turkish and Azeri dotted I
Turkish has two letters that English speakers think of as one. The capital I pairs with the dotless lowercase ı. The capital İ (with a dot) pairs with the ordinary i. English-style lower() gets this wrong for Turkish.
print("I".lower()) # i (a Turkish reader expects ı)
print(len("\u0130".lower())) # 2 (i plus a combining dot above)
print("\u0130".casefold() == "i\u0307") # TruePython's lower() and casefold() do not take a locale argument. They apply the language-neutral rules. If you must handle Turkish text correctly, use a library with locale-aware case operations, such as ICU bindings (PyICU). Otherwise you should know that this is a limit of the built-in methods.
Folding does not normalise
casefold() changes letters. It does not change how an accented letter is built from code points. The next chapter covers composed and decomposed forms in detail, but the interaction matters here.
import unicodedata
def nfd(s):
return unicodedata.normalize("NFD", s)
def caseless_equal(a, b):
return nfd(nfd(a).casefold()) == nfd(nfd(b).casefold())
upper_composed = "\u00c9" # É as one code point
lower_decomposed = "e\u0301" # e followed by a combining acute accent
print(upper_composed.casefold() == lower_decomposed.casefold()) # False
print(caseless_equal(upper_composed, lower_decomposed)) # TrueThe first comparison is false. After folding, the first string is the single code point é and the second is still e plus an accent. They look the same and are not equal.
caseless_equal follows the recipe in the Unicode Standard for canonical caseless matching: normalise to NFD, fold, then normalise to NFD again. The second normalisation is needed because folding can produce sequences that are not in normal form. For most real text one pass is enough. For a matching function that must be correct, use the full recipe.
Which operation to use
The middle branch gets its own section near the end of this chapter. For now, note that case operations belong to matching and counting, not to display.
Case-insensitive matching in practice
Here is a small helper that wraps the recipe, with a lookup table built on top of it. This is the common use: a dictionary or set whose keys are compared without regard to case.
import unicodedata
def match_key(text):
"""Return a key that is equal for strings that differ only by case or by
canonical Unicode form."""
nfd = lambda s: unicodedata.normalize("NFD", s)
return nfd(nfd(text).casefold())
cities = ["Stra\u00dfburg", "M\u00fcnchen", "K\u00f6ln"]
index = {match_key(name): name for name in cities}
query = "STRASSBURG"
print(index.get(match_key(query))) # Straßburg
print(index.get(match_key("MU\u0308NCHEN"))) # MünchenThe index stores the display form as the value and the match key as the lookup. That separation is the habit to build. You keep the original text for output and use the key for comparison.
Regular expressions and `re.IGNORECASE`
The re.IGNORECASE flag does something different from casefold(). In Python's re module, case-insensitive matching on str patterns uses one-to-one case equivalences. It will match É with é, but it will not match ß with ss, because that would need a one-to-many mapping. If your pattern must behave like a fold, fold the text and the pattern first, then match without the flag.
Common errors
- Using
lower()for comparison. It passes English tests and breaks onß, final sigma, and the ligatures. - Using
upper()for comparison. It has the same class of problem."ß".upper()is"SS", but the round trip back throughlower()does not recoverß. - Comparing a folded string to an unfolded one. Fold both sides, or fold at the entry point and never compare against raw input.
- Storing only the folded text. Folding is lossy.
"Stra\u00dfe"and"STRASSE"both become"strasse", and you cannot recover which one the author wrote. Keep the original. - Assuming the length stays the same.
casefold()can make a string longer. Offsets computed on the folded text do not line up with the original. If you need to highlight matches in the source, map positions back before you fold or search on the original with a different strategy. - Folding and then matching against a stop word list or vocabulary that is not folded. Both sides must go through the same steps. A list containing "Straße" will never match the folded token "strasse".
- Ignoring scripts without case. Chinese, Japanese, Korean, Arabic, Hebrew, and Thai have no upper and lower case. Folding leaves them unchanged. That is correct, and no extra handling is needed.
When lowercasing hurts the task
Case folding removes information, and some tasks need that information.
- Named entity recognition often relies on capitalisation. "Apple announced" and "an apple a day" have different readings, and a model can use the capital letter as a clue.
- Sentiment analysis can use shouting. "This is TERRIBLE" carries more intensity than "this is terrible".
- Acronyms change meaning. "US" and "us", or "IT" and "it", collapse into one token after folding.
- Code and identifiers are case-sensitive. Folding
userIdanduseridtogether is wrong in a case-sensitive language.
A search system is the opposite case. A user typing "python" expects to find "Python", so folding on both the index and the query is standard. A common compromise for modelling is to fold the text for features but keep a separate flag, such as "was the word all capitals", so the signal survives. The last chapter of this tutorial returns to these task trade-offs.
Summary of the rules
- Use
casefold()for comparison and counting. Uselower()andupper()for display. - Fold both sides of every comparison, and fold the stop word list and vocabulary too.
- Normalise Unicode alongside folding, because folding does not unify composed and decomposed forms.
- Keep the original text. Store the key separately.
- Built-in methods are not locale-aware. Turkish and Azeri need a locale-aware library.
- Skip folding when capitalisation is a signal for the task.
Exercise
A colleague writes tokens = [t.lower() for t in tokens] and then checks "strasse" in tokens to find the word "Straße" in German text. Why does the check fail on the input "Die Straße ist lang", and what is the smallest change that fixes it for this input?
Show answer
"Straße".lower() is "straße", because ß is already lowercase and lower() leaves it alone. So the list contains "straße", not "strasse", and the membership test is false. Changing t.lower() to t.casefold() maps ß to ss, so the token becomes "strasse" and the check succeeds. For fully robust matching you would also normalise to NFD before and after folding, because an accented word could arrive in decomposed form.
Exercise
Predict the output of these lines, then say what the last line shows about comparing folded and unfolded text. word = "ΟΔΥΣΣΕΥΣ" print(word.lower() == "οδυσσευς") print(word.casefold() == "οδυσσευς") print(word.casefold() == "οδυσσευς".casefold())
Show answer
The first line prints True, because lower() picks the final sigma ς at the end of the word. The second prints False, because casefold() turns every sigma, including the final one, into σ, so it no longer equals a string ending in ς. The third prints True, because both sides were folded. The lesson is that a folded string must only be compared with another folded string.
Exercise
Write a function unique_ci(words) that returns the words with case-insensitive duplicates removed. It should keep the first spelling it sees and should treat "Straße" and "STRASSE" as duplicates. Use the full canonical caseless recipe for the key.
Show answer
import unicodedata def key(text): nfd = lambda s: unicodedata.normalize("NFD", s) return nfd(nfd(text).casefold()) def uniqueci(words): seen = set() result = [] for w in words: k = key(w) if k not in seen: seen.add(k) result.append(w) return result print(uniqueci(["Stra\u00dfe", "STRASSE", "Haus", "haus"])) # ['Straße', 'Haus']