Normalize both strings with .casefold() (a.casefold() == b.casefold()) for accurate Unicode-wide case-insensitive equality (including characters like German "ß" $\leftrightarrow$ "ss" and Greek "ς" $\leftrightarrow$ "σ"), or use .lower() (a.lower() == b.lower()) when you are strictly comparing plain ASCII strings and want a slight speed advantage.
Basic Example
a = "Straße"
b = "STRASSE"
# 1. Recommended: Use .casefold() for full Unicode case-insensitive comparison
print(a.casefold() == b.casefold()) # Output: True
# Why .lower() fails on non-ASCII Unicode edge cases:
print(a.lower() == b.lower()) # Output: False ('straße' != 'strasse')
# 2. Normalizing user input / CLI commands (strip whitespace + casefold):
command = " Yes "
if command.strip().casefold() == "yes":
print("Confirmed") # Output: Confirmed
# 3. Case-insensitive membership check against a set of normalized strings:
allowed_roles = {"admin", "editor", "viewer"}
user_role = "ADMIN"
print(user_role.casefold() in allowed_roles) # Output: True
Key Details & Edge Cases
- Why
.casefold()beats.lower()for Unicode text:.lower()only maps each character to its lowercase code point, leaving characters without a distinct lowercase form unchanged ("ß".lower()stays"ß", whereas"SS".lower()becomes"ss")..casefold()implements the full Unicode Case Folding standard specifically designed for caseless matching ("ß".casefold()$\rightarrow$"ss","ff".casefold()$\rightarrow$"ff","ς".casefold()$\rightarrow$"σ").
- Normalize Unicode accents/diacritics first with
unicodedata.normalize("NFC", s)when comparing international text:- Visually identical accented characters can be encoded either as a single precomposed code point (
"é",U+00E9) or as a base letter plus combining accent ("e\u0301"), which.casefold()alone considers unequal. Normalize both strings first:import unicodedata def norm_eq(s1: str, s2: str) -> bool: return ( unicodedata.normalize("NFC", s1).casefold() == unicodedata.normalize("NFC", s2).casefold() )
- Visually identical accented characters can be encoded either as a single precomposed code point (
- Avoid calling
.casefold()repeatedly inside loops or sorting keys:- When checking membership across a large collection, store pre-folded strings in a
set(valid = {x.casefold() for x in raw_items}) so each lookup runs in $O(1)$ without re-folding the collection. When sorting strings case-insensitively, passkey=str.casefold(sorted(words, key=str.casefold)).
- When checking membership across a large collection, store pre-folded strings in a
- Locale-specific casing (e.g., Turkish dotted
İ/ dotlessı):- Both
.casefold()and.lower()use locale-independent Unicode rules ("I".casefold()$\rightarrow$"i", not Turkish dotless"ı"). If your application requires locale-specific collation or Turkish casing rules, use the third-partyPyICU(icu.Collator) library.
- Both
- Case-insensitive regex matching (
re.IGNORECASE/re.I):- When matching patterns rather than exact whole strings, pass
flags=re.IGNORECASE(re.search(r"error", line, flags=re.IGNORECASE)), which uses Unicode-aware case folding by default in Python 3.
- When matching patterns rather than exact whole strings, pass
Comparison of Case-Insensitive String Comparison Approaches
| Approach | Handles Unicode ("ß" == "SS", "ς" == "Σ")? |
Handles Combining Accents ("é" vs "e\u0301")? |
Best Used When |
|---|---|---|---|
a.casefold() == b.casefold() (Recommended) |
Yes | No (pair with unicodedata.normalize("NFC", ...) if needed) |
Default choice for all general-purpose case-insensitive equality, usernames, emails, and search queries. |
a.lower() == b.lower() |
No (ASCII-safe only) | No | Hot loops comparing guaranteed ASCII-only identifiers, HTTP headers, or hex strings. |
sorted(items, key=str.casefold) |
Yes | No | Case-insensitive alphabetical sorting without mutating the original strings. |
re.search(pat, s, flags=re.IGNORECASE) |
Yes | No | Substring, prefix/suffix, or regular expression pattern matching ignoring case. |
You must log in or register to comment.
