Python String casefold() Method

By Lenin Mishra

If you prefer to watch Youtube videos over reading blogs, check out our video on Python strings here.

The casefold() method in Python returns a case folded copy of a string where all characters are lowercase.

Code

str1 = "Pylenin writes about Python."

print(str1.casefold())

Output

pylenin writes about python.

The casefold() method is similar to lower() method. However, it is more aggresive.

casefold() method is best suited for caseless matching.

What is Caseless Matching?

Caseless Matching is a way of erasing case differences in strings by mapping characters of different cases to a single form.

For example, the German lowercase letter is equivalent to ss.

Let’s look at the example below.

Code

str1 = "Pylenin has a nice dress."
str2 = "Pylenin has a nice dre�."

# Experiment with lower()
print(str1.lower() == str2.lower())

# Experiment with casefold
print(str1.casefold() == str2.casefold())

Output

False
True

While the lower() method was unable to convert the german character, casefold() method converted it successfully and hence showed that both the strings are the same.

Check out other commonly used Python string methods.

  1. How to create a string in Python?
  2. How to access characters in a Python string?
  3. How to replace characters in a string in Python?
  4. How to concatenate strings in Python?
  5. How to iterate through a string in Python?
  6. Check if a Substring is Present in a Given String in Python
  7. Escape sequences in Python String
  8. Python String Formatting - The Definitive Guide