Skip to main content

Python String casefold() Function

The String casefold() method converts all characters of the string into lowercase letters and returns a new string.

note

This method does not change the original string.

note

Casefolded strings are usually used to normalize text for the purposes of caseless comparison (especially when you want to take characters of many different languages into account).

Syntax

my_string.casefold()

casefold() Parameters

Python String casefold() function does not take any parameters.

casefold() Return Value

Python String casefold() function returns

Examples

Example 1: Casefold a String with casefold() method

The capitalize() method is used to convert the first character of the sentence string to uppercase and the other characters to lowercase.

For example:

my_str = 'tUtORIALReFErEnCe'
result = my_str.casefold()
print(result) # Output: tutorialreference

output

tutorialreference

Example 2: Casefold a String with Non-Alphabetic Characters

If the string has characters that are non-alphabeitc, these characters are kept unchanged while the rest of the string is changed to lowercase.

my_str = '123 Is A Number.'
result = my_str.casefold()
print(result) # Output: 123 is a number.

output

123 is a number.

Example 3: casefold() does Not Change the Original String

The casefold() method returns a new string and does not modify the original string.

For example:

my_str = 'tUtORIALReFErEnCe'
result = my_str.casefold()

print(f"Before casefold(): {my_str}") # Output: Before casefold(): tUtORIALReFErEnCe
print(f"After casefold(): {result}") # Output: After casefold(): tutorialreference

output

Before casefold(): tUtORIALReFErEnCe
After casefold(): tutorialreference

casefold() method vs lower() method

The casefold() method is similar to the lower() method but it is more aggressive, because it is intended to remove all case distinctions in a string.

For example, the German lowercase letter ß is equivalent to ss. Since it is already lowercase, lower() would do nothing to ß, but casefold() converts it to ss.

my_str = 'Das straße'
result = my_str.casefold()
print(result) # Output: das strasse

my_str = 'Das straße'
result = my_str.lower()
print(result) # Output: das straße

output

das strasse
das straße
warning

If you are working strictly in the English language, lower() and casefold() returns exactly the same results.

However, if you are trying to normalize text from other languages that use more than English 26-letter alphabet, use casefold() to compare your strings for more consistent results.