Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
casefold() string in Python
The casefold() method in Python converts a string to lowercase, making it ideal for case-insensitive string comparisons. Unlike lower(), casefold() handles special Unicode characters more aggressively, making it the preferred choice for string matching.
Syntax
string.casefold()
This method takes no parameters and returns a new string with all characters converted to lowercase.
Basic Usage
Here's how to convert a string to lowercase using casefold() ?
string = "BestTutorials"
# print lowercase string
print("Lowercase string:", string.casefold())
Lowercase string: besttutorials
Case-Insensitive String Comparison
You can compare two strings with different cases by applying casefold() to both ?
string1 = "Hello Tutorials"
string2 = "hello tutorials"
string3 = string1.casefold()
string4 = string2.casefold()
if string3 == string4:
print("Strings are equal after casefold()")
else:
print("Strings are not equal")
Strings are equal after casefold()
casefold() vs lower()
While both methods convert to lowercase, casefold() is more aggressive with special characters ?
# German eszett character
text = "Straße"
print("lower():", text.lower())
print("casefold():", text.casefold())
print("Are they equal?", text.lower() == text.casefold())
lower(): straße casefold(): strasse Are they equal? False
Comparison
| Method | Purpose | Unicode Handling | Best For |
|---|---|---|---|
lower() |
Basic lowercase conversion | Standard | Simple text formatting |
casefold() |
Aggressive lowercase for comparisons | Enhanced | Case-insensitive matching |
Conclusion
Use casefold() for case-insensitive string comparisons, especially with international text. It provides more reliable results than lower() when dealing with special Unicode characters.
