How to Compare Strings with casefold in Python

Compares two strings ignoring case differences using the casefold() method for proper Unicode normalization.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

12 lines
Python 3.9+
def 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

stdout
'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

  1. Use str.casefold() with .strip() to compare trimmed values without surrounding whitespace.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.