Python String casefold()

Filed Under: Python String

python string casefold
Python string casefold() function returns a casefolded copy of the string. This function is used to perform case-insensitive string comparison.

Python String casefold()

Let’s look at a simple example of casefold() function.

s = 'My name is Pankaj'


s1 = 'Python'
s2 = 'PyThon'
print(s1.casefold() == s2.casefold())


my name is pankaj

From above program, casefold() function looks exactly same as string lower() function. Actually, it’s effect is same when string is made of ASCII characters.

However, casefolding is much more aggressive and it’s intended to remove all case distinctions in a string.

For example, the German lowercase letter ‘ß’ is equivalent to “ss”. Since it’s already lowercase, lower() would do nothing to ‘ß’ but casefold() will convert it to “ss”.

Let’s look at another example to confirm this behavior.

s1 = 'ß'  # typed with Option+s in Mac OS
s2 = 'ss'
s3 = 'SS'
if s1.casefold() == s2.casefold():
    print('s1 and s2 are equals in case-insensitive comparison')
    print('s1 and s2 are not-equal in case-insensitive comparison')

if s1.casefold() == s3.casefold():
    print('s1 and s3 are equals in case-insensitive comparison')


s1 and s2 are equals in case-insensitive comparison
s1 and s3 are equals in case-insensitive comparison
You can checkout more Python String examples from our GitHub Repository.

Reference: Official Documentation

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors