Python String casefold() Method
The casefold()
method returns a case-folded version of the string. It is similar to the lower()
method but more aggressive in terms of case conversion.
Syntax
string.casefold()
Parameters
No parameters
Return Value
Returns a new string with all characters casefolded (converts more characters to lowercase equivalents than lower()
).
Examples
Basic Usage
text = "HELLO"
print(text.casefold()) # Output: hello
Comparison with lower()
text = "Straße" # German for street
print(text.lower()) # Output: straße
print(text.casefold()) # Output: strasse
For basic English or ASCII texts, lower()
and casefold()
usually produce the same results. However, the difference becomes significant when working with other languages or Unicode text.
In the above example, the German letter "ß"
is unchanged by lower()
, but casefold()
converts it to "ss"
, which is the correct form for case-insensitive comparisons in German.
Case-insensitive Comparison
The casefold()
method removes all case distinctions making it suitable for case-insensitive comparison.
text = "Straße" # German for street
text2 = "STRASSE"
print(text.lower() == text2.lower()) # False
print(text.casefold() == text2.casefold()) # True