str.casefold()
Returns a version of a string made for case-insensitive comparison. Stronger than lower() for text in any language.
str.casefold()casefold() is like str.lower(), but goes further: its goal is not nice-looking text but making two strings that differ only in case turn into exactly the same string.
For English the two give the same result. The difference shows up with special letters: the German ß becomes ss, so "Straße" and "STRASSE" match after casefold() but not after lower().
Use casefold() when you compare or search text a user typed, such as names, cities or tags. Do not use it for text you show on screen: it can change how words are spelled.
Return value
A new string ready for case-insensitive comparison.
Examples
1Same as lower() for English
print("Hello World".casefold())
print("Hello World".lower())hello world hello world
2Where lower() is not enough
a = "Straße"
b = "STRASSE"
print(a.lower() == b.lower())
print(a.casefold() == b.casefold())
print(a.casefold())False True strasse
3A case-insensitive search
cities = ["Zürich", "MÜNCHEN", "Graz"]
query = "münchen"
for c in cities:
if c.casefold() == query.casefold():
print("Found:", c)Found: MÜNCHEN
4Remove duplicate tags typed in different case
tags = ["Python", "PYTHON", "python", "Data"]
seen = []
for t in tags:
if t.casefold() not in [s.casefold() for s in seen]:
seen.append(t)
print(seen)['Python', 'Data']
Common mistakes
Showing casefolded text to users
casefold() is for comparing, not for display: it can change spelling. Compare with the casefolded version, but keep and show the original.
street = "Hauptstraße"
print(street.casefold())
print(street)hauptstrasse Hauptstraße
Questions people ask
casefold() vs lower(): which is better?
For comparisons, casefold(): it handles more languages. For display, lower().
Does casefold() remove accents?
No. "é" stays "é". To ignore accents, use unicodedata.normalize("NFD", text) and drop the combining marks.
Is there a casefold() for checking only?
No iscasefolded() exists. Compare: text == text.casefold().