How to Compare Strings with casefold in Python
Compares two strings ignoring case differences using the casefold() method for proper Unicode normalization.
Python code
12 linesdef compare_strings(str1: str, str2: str) -> bool:
return str1.casefold() == str2.casefold()
if __name__ == "__main__":
tests = [
("HELLO", "hello"),
("Straße", "STRASSE"),
("Python", "Python"),
("Mixed Case", "mixed case"),
]
for s1, s2 in tests:
print(f"{s1!r} == {s2!r}: {compare_strings(s1, s2)}")
Output
'HELLO' == 'hello': True
'Straße' == 'STRASSE': True
'Python' == 'Python': True
'Mixed Case' == 'mixed case': True
How it works
The str.casefold() method is an aggressive lowercase transformation designed specifically for caseless comparison. It handles Unicode characters better than lower(), such as converting the German 'ß' to 'ss', which matches the uppercase 'SS'. This makes it the recommended approach when you need to compare strings in a case-insensitive manner across different languages and scripts.
Common mistakes
- Using .lower() instead of .casefold(), which fails for characters like ß that have no simple lowercase mapping.
- Forgetting to call the method on both strings before comparing, leading to inconsistent results.
- Assuming casefold is the same as lowercase for all supported Unicode characters.
Variations
- Use str.casefold() with .strip() to compare trimmed values without surrounding whitespace.
- Use unicodedata.normalize('NFKC', ...) before casefold for full Unicode normalization.
Real-world use cases
- Validating user input like email addresses or usernames in a case-insensitive login system.
- Building search functionality that matches keywords regardless of capitalization or Unicode variants.
- Sorting or grouping locale-specific text data where casefold ensures consistent comparison.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.