Python String casefold() Method



The Python string casefold() method converts all characters in the string to lowercase. It also performs additional transformations to handle special cases, such as certain Unicode characters that have different representations in uppercase and lowercase.

The resulting casefolded string is suitable for performing case-insensitive comparisons using methods like == or in.

Syntax

Following is the basic syntax of the Python String casefold() method −

string.casefold()

Parameter

This method does not accept any parameters.

Return Value

The method returns a new string that is the lowercase equivalent of the original string.

Example

In the following example, we are converting the string "Hello World" to lowercase using the casefold() method −

text = "Hello World"
result = text.casefold()
print(result)    

Output

The output obtained is as follows −

hello world

Example

This example shows that the casefold() method does not affect symbols or punctuation in the string. Only alphabetical characters are converted to lowercase −

text = "Hello, World!"
result = text.casefold()
print(result)       

Output

Following is the output of the above code −

hello, world!

Example

We can also use the casefold() method for case-insensitive comparisons. The method compares two strings after converting them to lowercase −

text1 = "hello"
text2 = "HELLO"
result = text1.casefold() == text2.casefold()
print(result)    

Output

The result produced is as shown below −

True

Example

Now, we are using the casefold() method with non-ASCII characters. It converts accented characters to their lowercase equivalents −

text = "Hèllò Wørld"
result = text.casefold()
print(result) 

Output

We get the output as shown below −

text = "hèllò wørld"
case_conversion.htm
Advertisements