The Python String casefold() method returns a case folded string, and we use this to remove all case distinctions in a string.
Let’s look at what this means.
Using the Python String casefold() method
This belongs to the
String class, and can be used only on String objects.
The Syntax for this method is:
This will return a new string, after applying all case folds.
For example, it will convert all uppercase letters to lowercase.
my_str = "Hello from AskPython" casefolded_str = my_str.casefold() print(casefolded_str)
hello from askpython
This converts all uppercase letters to lowercase ones for the English alphabet.
But what if the string has characters from another language, and in another encoding? The Python string casefold() method solves this problem.
Take an example of the German lowercase letter ‘
ß ‘. This corresponds to the English string “ss”, since there is an encoding for German alphabets, and we decode it to an English string.
If we were to use the
lower() method on this alphabet, it would do nothing, since the letter is already in lowercase, so the output will remain ‘
ß ‘. Python string casefold() not only converts to lowercase, but also makes sure we get back our English string “ss”.
The below screenshot shows this difference.
Let’s take one more example, to show that the strings ‘
ß‘ and “SS” will resolve to the same casefolded string “ss”.
s1 = 'ß' s2 = 'ss' s3 = 'SS' if s1.casefold() == s2.casefold(): print('Casefolded strings of s1 and s2 are equal') else: print('Casefolded strings of s1 and s2 are not equal') if s1.casefold() == s3.casefold(): print('Casefolded strings of s1 and s3 are equal')
Casefolded strings of s1 and s2 are equal Casefolded strings of s1 and s3 are equal
Indeed, both these strings resolve to the same casefolded string!
In this article, we learned how we could use the Python string casefold() method in Python.