Sub topic 7
Case-insensitive searching and casefold
This chapter assumes you know how in, find, count, and startswith work, and that lower() and upper() return new strings. It covers how to make those searches ignore case correctly, and why lower() is sometimes the wrong tool.
Why case-insensitive matching needs care
Search methods compare characters exactly, so "Python" and "python" are different strings:
text = "Python is fun"
print("python" in text) # False
print(text.startswith("py")) # False
print(text.count("PYTHON")) # 0The usual fix is to convert both sides to one case before comparing. The question is which conversion to use. lower() is the first thing most people reach for. For plain English text it works. For text in other languages it can give wrong answers.
The basic pattern: fold both sides
Convert the haystack and the needle with the same method, then use the ordinary search tools.
haystack = "Error: Disk Full"
needle = "disk"
print(needle.casefold() in haystack.casefold()) # True
print(haystack.casefold().startswith("error")) # True
print(haystack.casefold().find("full")) # 12
print("Banana BANANA".casefold().count("an")) # 4Folding only one side is a common bug. "Disk" in haystack.lower() is False even though the haystack contains disk, because the needle still has a capital D.
The original string is untouched, as with every str method. The folded copy is a temporary value used only for the comparison.
What casefold does that lower does not
str.lower() maps each character to its lowercase form for display purposes. str.casefold() follows the Unicode case-folding rules, which are designed for comparison. Folding is more aggressive, and it can change the length of the string.
print("Straße".lower()) # straße
print("Straße".casefold()) # strasse
print("Straße".casefold() == "STRASSE".casefold()) # True
print("Straße".lower() == "STRASSE".lower()) # FalseThe German letter ß is already lowercase, so lower() leaves it alone. "STRASSE".lower() gives "strasse", which does not equal "straße". casefold() turns ß into ss, so both spellings meet at the same result.
| Input | `lower()` | `casefold()` | Why they differ |
|---|---|---|---|
| `"HELLO"` | `hello` | `hello` | Plain ASCII behaves the same |
| `"ß"` | `ß` | `ss` | Folding expands one character to two |
| `"ς"` (final sigma) | `ς` | `σ` | Folding merges the two Greek lowercase sigmas |
| `"Σ"` | `σ` | `σ` | Both agree here |
The Greek example shows the same idea. Greek has two lowercase forms of sigma, and casefold() maps both to σ, so words written either way compare as equal.
print("ς" == "σ") # False
print("ς".casefold() == "σ".casefold()) # TrueFor ASCII-only data, lower() and casefold() give identical results. Using casefold() anyway costs almost nothing and protects you when non-English text shows up later.
Edge case: positions change after folding
Because folding can change the length, an index found in the folded string may not match the same position in the original.
original = "Straße x"
folded = original.casefold()
print(original.find("x")) # 7
print(folded.find("x")) # 8
print(original[folded.find("x")]) # IndexErrorThe last line raises IndexError because index 8 is past the end of the 8-character original (valid indices are 0 to 7). Even when no error occurs, slicing the original with an index from the folded copy can pick the wrong characters.
Use a folded copy to answer yes-or-no questions and counts. If you need the position in the original text, you have two options:
- Use
re.searchwithre.IGNORECASE, which reports positions in the original string. It uses simpler per-character case rules thancasefold(), so it will not treatßandssas equal. - Compare character by character over the original string yourself. This is only worth it for specialized tools.
import re
original = "Hello, WORLD"
match = re.search("world", original, re.IGNORECASE)
print(match.start()) # 7
print(original[match.start():match.end()]) # WORLDThe last chapter of this tutorial returns to the limits of string methods and when re is the better choice.
Case-insensitive comparison in other places
Searching is one use. The same folding idea applies wherever you compare strings.
Sorting with a key function that folds each item:
words = ["banana", "Cherry", "apple"]
print(sorted(words)) # ['Cherry', 'apple', 'banana']
print(sorted(words, key=str.casefold)) # ['apple', 'banana', 'Cherry']Passing str.casefold as the key calls the method on each element. The default sort puts every uppercase letter before every lowercase one, which is rarely what a reader expects.
Dictionary lookups, where you fold the keys when you store them and fold the query when you read:
colors = {}
for name, code in [("Red", "#f00"), ("GREEN", "#0f0")]:
colors[name.casefold()] = code
query = "green"
print(colors.get(query.casefold())) # #0f0
print(colors.get("RED".casefold())) # #f00If you only fold at lookup time, keys such as "Red" stay in their original case and the lookup of "red" fails.
Membership checks against a list of allowed values:
allowed = {"yes", "y", "true"}
answer = " YES ".strip().casefold()
print(answer in allowed) # TrueHere strip() removes the stray whitespace and casefold() handles the case. Putting the allowed values in a set makes the check fast, and it only works because they are already stored in folded form.
A decision path
Casefold does not fix accents
Some characters have more than one valid Unicode representation. The letter é can be one code point, or an e followed by a combining accent. They look identical but are different strings, and casefold() does not merge them.
a = "caf\u00e9" # é as a single code point
b = "cafe\u0301" # e plus a combining acute accent
print(a == b) # False
print(a.casefold() == b.casefold()) # False
print(len(a), len(b)) # 4 5The standard library module unicodedata can normalize both strings to a common form first. This function follows the Unicode recommendation for canonical caseless matching: normalize, fold, then normalize again.
import unicodedata
def caseless_equal(x, y):
def key(s):
s = unicodedata.normalize("NFD", s)
s = s.casefold()
return unicodedata.normalize("NFD", s)
return key(x) == key(y)
print(caseless_equal("caf\u00e9", "CAFE\u0301")) # True
print(caseless_equal("Straße", "STRASSE")) # True
print(caseless_equal("cafe", "café")) # FalseThe last line is False on purpose. This function ignores case but still treats e and é as different letters. Removing accents is a separate and lossy operation, and you should only do it when the application calls for it.
Locale limits
casefold() does not know about language-specific rules. Turkish, for example, pairs dotted and dotless i differently from English, and no built-in str method handles that. If your application must follow a particular language's rules, use a dedicated library such as PyICU. For general matching of user input, casefold() is the right default.
Common mistakes
- Folding only one side of the comparison.
- Using
lower()for comparison when the data may contain non-English text. - Using an index from a folded string to slice the original.
- Storing the folded text and showing it to users. Fold for matching and keep the original for display.
- Expecting
casefold()to handle accent differences or locale rules.
Practice
Exercise
A log line is "WARNING: Disk almost FULL". Write two expressions: one that checks whether the line contains "full" regardless of case, and one that checks whether it starts with "warning" regardless of case. Then explain why line.find("FULL".casefold()) would not work.
Show answer
Use "full" in line.casefold() and line.casefold().startswith("warning"). The call line.find("FULL".casefold()) folds only the needle to "full" but searches the original line, which contains uppercase FULL. The search is case-sensitive, so it returns -1. The haystack must be folded too: line.casefold().find("full").
Exercise
Given names = ["bob", "Alice", "carol"], what does sorted(names) return, and how do you sort them alphabetically ignoring case? Why does "Straße".lower() == "STRASSE".lower() return False, while the same comparison with casefold() returns True?
Show answer
sorted(names) returns ['Alice', 'bob', 'carol'] because uppercase letters sort before lowercase ones. Use sorted(names, key=str.casefold) to get ['Alice', 'bob', 'carol'] by true alphabetical order, which matters when mixed-case names would otherwise be split apart. The lower() comparison is False because lower() leaves ß unchanged, giving "straße" against "strasse". casefold() expands ß to ss, so both sides become "strasse".