Casefold Compares Text Case Insensitively

str.casefold folds locale-specific letters like German ß to their base form, so case-insensitive matching outlives what str.lower() gets wrong.

PythonData Integrity

Code

pythonsnippet
13 lines
# lower() 不认识德语 ß:casefold 才是无大小写比较(case-insensitive)的正确工具
print("straße".lower() == "strasse")
print("straße".casefold() == "strasse")

# casefold 对希腊字母也归得更彻底:句尾 Σ 折成普通 σ,lower 则保留变体
print("ΣΊΣΥΦΟΣ".casefold())
print("ΣΊΣΥΦΟΣ".lower())

# 做查找键的归一化:同一条目不再因大小写漏配
aliases = {"Departement": "dept", "Strasse": "street"}
query = "STRASSE"
match = next((k for k in aliases if k.casefold() == query.casefold()), None)
print("matched:", match)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

False
True
σίσυφοσ
σίσυφος
matched: Strasse

The code in motion

Module-level bindings hold the data — aliases, query, match — with no function scope in between.

Applying it

Running the file prints labeled results such as straße, ΣΊΣΥΦΟΣ, matched: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. Its state lives in module-level bindings: `aliases`, `query`, `match`.