Python casefold() Method

Definition
In Python, casefold() returns a case-folded copy of a string for case-insensitive matching. It is stronger than lower() for Unicode text.
It takes no arguments. Fold both sides before you compare, and keep the original text for display.
Syntax
Call casefold on the string. Start with this line.
| Call | What it does |
|---|
"Hello".casefold() | Returns a folded form for matching. |
a.casefold() == b.casefold() | Case-insensitive equality check. |
Prefer casefold() over lower() when international text may appear.
Library declarations
Parameters
This method has no parameters.
Return Value
| Return Value | Description |
|---|
| str | A new case-folded string for comparisons. |
Python Examples
Example 1 — Basic casefold()
Fold uppercase text and confirm the original string stays unchanged.
original = "HELLO"
folded = original.casefold()
print("Original:", original)
print("Casefolded:", folded)
Original: HELLO
Casefolded: hello
How It Works
- Start uppercase.
original is "HELLO". - Call casefold. Returns a new folded string into
folded. - ASCII looks like lower. Result is
"hello". - Source untouched. Immutability keeps
original as "HELLO".
Example 2 — Case-Insensitive Comparison
Accept any casing of the same word by folding before ==.
answer = "PyThOn"
if answer.casefold() == "python":
print("Correct! Case did not matter.")
else:
print("Try again.")
Correct! Case did not matter.
How It Works
- Mixed input. User typed
"PyThOn". - Fold the answer. Becomes
"python". - Compare to a folded target. Literal
"python" is already folded. - Match succeeds. Letter case no longer blocks equality.
Example 3 — casefold() vs lower()
The classic Unicode win: German ß folds to ss.
word_a = "Straße"
word_b = "STRASSE"
print("lower(): ", word_a.lower() == word_b.lower())
print("casefold():", word_a.casefold() == word_b.casefold())
lower(): False
casefold(): True
How It Works
- lower() keeps ß.
"Straße".lower() → "straße", not equal to "strasse". - casefold() expands ß. Maps eszett to
ss → "strasse". - STRASSE folds too. Becomes
"strasse". - Equality holds. Prefer
casefold() for real-world matching.
Frequently Asked Questions
It returns a case-folded copy of a string for case-insensitive matching.
For ASCII they often match. casefold() applies stronger Unicode rules, such as German ß → ss.
Use it for case-insensitive compares, search, usernames, and international text.
No. It returns a new string.
Python 3.3 and later.
Next: center()
Center text within a fixed width using padding characters.
center() →About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful