The casefold() method in Python is a way to make a string all lowercase. It’s like the lower() method, but even better because it can handle more special cases. This is especially useful when you want to compare two strings and don’t want to worry about whether they are in uppercase or lowercase.
string.casefold()
Here’s an example of using the casefold() method:
str1 = "Hello World!"
str1_casefolded = str1.casefold()
print(str1_casefolded)
Output:
hello world!
Example 1
Compare the casefolded() versions of the strings.
str1 = "Python is Fun"
str2 = "PYTHON IS FUN"
if str1.casefold() == str2.casefold():
print("The strings are the same.")
else:
print("The strings are different.")
Output:
The strings are the same.
Example 2
Compare the special characters string with casefolded().
str1 = "Straße" # The German word for 'street', includes a special character
str2 = "STRASSE" # The same word, but with the special character replaced
if str1.casefold() == str2.casefold():
print("The strings are the same.")
else:
print("The strings are different.")
Output:
The strings are the same.
Example 3
The program then uses the casefold() method to change what the user typed to all lowercase letters. This means that no matter how the user types ‘yes’ or ‘no’ (for example, ‘Yes’, ‘YES’, ‘yes’, ‘No’, ‘NO’, or ‘no’), the program will understand it correctly.
# Getting a user's input
user_input = input("Please enter 'yes' or 'no': ")
# Making the decision case-insensitive using casefold
if user_input.casefold() == 'yes':
print("You entered yes.")
elif user_input.casefold() == 'no':
print("You entered no.")
else:
print("Invalid input.")