What is the String casefold() method in Python?

String casefold() method

To create caseless string matching, the Python String casefold() technique is utilized.

The casefold() method removes any case distinctions present in the given string. It’s used for caseless matching, which means it ignores cases when comparing.

The casefold() method is similar to the lower() method, but more aggressive.

Syntax

string.casefold()

Parameter values

The method casefold() takes no parameters.

Return value

The casefold() method returns the case folded string.

Code

The following code shows how to use the casefold() method in Python:

Example 1

Convert string to lowercase using the casefold() method.

string = "PYTHON IS A PROGRAMMING LANGUAGE"
# print lowercase string
print("Lowercase string:", string.casefold())

Example 2

Compare strings using the casefold() method.

str1 = "Fluß"
str2 = "Fluss"
# ß is equivalent to ss
if str1.casefold() == str2.casefold():
print('The strings are equal.')
else:
print('The strings are not equal.')

The German lowercase letter ß is equivalent to ss.

In the above code, the if statement is passed the casefold() method, which compares the strings. Under the hood, the casefold() method automatically converts ß to ss, since it is equivalent.

Free Resources