Returns a casefolded copy of the string.
- Finding whether two strings of characters match, is a common requirement in information processing. Often the texts to be compared may not be of the same case. To perform a case insensitive matching of strings it is first required to convert all the characters to a uniform case.
- The method casefold() does this - makes all the characters of a given string either lowercase or uppercase.
- Note that in Python strings are Unicode code points of the characters which are flexibly represented using one of the encoding schemes like UTF-8, UTF-16 and so on.
- While calling lower() results in simple mapping to lower case letters and calling upper() results in simple mapping to upper case letters calling casefold() results in removing the case as per Unicode standards (including the stability property and case tailoring as per Unicode standards).
- An example of the uppercase conversion during case folding happens for Cherokee lowercase letters. The Cherokee pronunciation YO is represented as the letter "Ᏺ" and defined with the code point U+13F2. The smaller case version of the letter is represented as "ᏺ" for which the code point is U+13FA. The casefold() method converts the string "Ᏺᏺ" to "ᏲᏲ" which has all the letters in uppercase.
# Example Python program that applies case folding
# From all Upper case
# From all lower case
# From title case
# From mixed case
Before casefolding an uppercased string: CHAPTER ONE
Result of casefolding an uppercased string: chapter one
Before casefolding a lowercased string: typographical
Result of casefolding an lowercased string: typographical
Before casefolding a titlecased string: Chapter Two
Result of casefolding a titlecased string: chapter two
Before casefolding a mixedcased string: How exquisitely the individual Mind
Result of casefolding a mixedcased string: how exquisitely the individual mind
Example 2 - When return values of casefold() and lower() differ:
# Example Python program that compares two strings from the German language
# Strings representing colors
# Compare two colors and print the results
# Perform a caseless comparison by converting both the strings to lowercase
# Perform a caseless comparison by mixing lowercase and casefold results
# Perform a caseless comparison by typecasing both the strings
Strings Weiß and weiß match:False
Strings weiß and weiß match:True
Strings weiß and weiss match - lower() vs casefold():False
Strings weiss and weiss match - casefold() vs casefold():True
Example 3 - When the return value of casefold() is in uppercase:
# Example python program that does casefolding for a
# Case folding results in all upper case letters
print("Unicode representation before and after applying casefolding:");
Cherokee string after case fold:
Unicode representation before and after applying casefolding: