Sub topic 7
Case-insensitive searching and casefold
This chapter assumes you know that str methods return new strings, and that you can use in, find, and lower. It builds on those to compare and search text without caring about case.
The simple approach: fold both sides
Python has no "ignore case" flag on in, find, or ==. The usual technique is to convert both strings to the same case first, then compare:
text = "Hello, World"
query = "WORLD"
print(query.lower() in text.lower()) # TrueBoth sides must be converted. Converting only one of them is a common bug, because "WORLD" in "hello, world" is False.
Why casefold instead of lower
lower is meant for display. It maps each uppercase letter to its lowercase form, and some characters have no such mapping. casefold is stricter and is designed for comparison. It also handles characters that expand into several letters. The German sharp s (ß) is the standard example:
print("Straße".lower()) # straße
print("Straße".casefold()) # strasse
print("Straße".casefold() == "STRASSE".casefold()) # True
print("Straße".lower() == "STRASSE".lower()) # FalseUse casefold whenever the goal is "are these the same text, ignoring case". Use lower when you want lowercase text to show or store.
| Method | Purpose | `"Straße"` becomes |
|---|---|---|
| `lower()` | Lowercase for display | `straße` |
| `casefold()` | Caseless comparison | `strasse` |
A reusable helper
Wrapping the pattern in a function keeps call sites readable and means you only fold in one place:
def contains_ci(text, query):
return query.casefold() in text.casefold()
def equals_ci(a, b):
return a.casefold() == b.casefold()
print(contains_ci("Hello, World", "WORLD")) # True
print(equals_ci("Straße", "STRASSE")) # TrueGotcha: positions refer to the folded string
casefold can change the length of a string. ß becomes ss, so an index found in the folded copy may not match the original:
s = "Straße Main"
print(s.find("Main")) # 7
print(s.casefold().find("main")) # 8If you need to slice or highlight the original text, do not reuse an index from the folded copy. When the text is plain ASCII, folding keeps the length, so the indexes match. For anything else, consider the re module with the re.IGNORECASE flag, covered in a later chapter.
Gotcha: casefold does not normalize
Unicode can write the same visible character in more than one way. The letter é can be one code point, or an e followed by a combining accent. casefold treats these as different. Normalize first with unicodedata:
import unicodedata
def fold(text):
return unicodedata.normalize("NFC", text).casefold()
a = "caf\u00e9" # é as a single code point
b = "cafe\u0301" # e plus a combining accent
print(a == b) # False
print(a.casefold() == b.casefold()) # False
print(fold(a) == fold(b)) # TrueFor user-facing search over mixed input, such as names typed by different people or pasted from different systems, a fold helper like this is a safe default.
Common errors
- Folding only one side of the comparison.
- Using
lowerwherecasefoldis needed, which breaks on characters likeß. - Using an index from the folded string to slice the original.
- Forgetting that visually identical text may differ in normalization form.
Exercise
Write a function startswithci(text, prefix) that returns True when text begins with prefix, ignoring case. Does startswithci("STRASSE 5", "Straße") return True?
Show answer
def startswithci(text, prefix): return text.casefold().startswith(prefix.casefold()) Yes. "Straße".casefold() is "strasse", and "STRASSE 5".casefold() is "strasse 5", which starts with it. With lower() the result would be False.