Python String casefold() – Case-Insensitive String Comparison

Python String casefold() Method

The casefold() method in Python is used to convert a string into a case-insensitive comparable form. It is more aggressive than lower() and is recommended for comparisons that ignore case, especially in international text.

Syntax

string.casefold()

Parameters:

  • None – casefold() does not take any parameters.

Returns:

  • A new string where all characters are converted to lowercase in a casefolded form (ready for case-insensitive comparison).

Example: Comparing Two Strings

str1 = "Straße"
str2 = "strasse"

print(str1.casefold() == str2.casefold())
True

Why? Because "ß" is casefolded to "ss" – something lower() doesn’t do.

Example: Basic Usage

text = "HELLO World"
print(text.casefold())
hello world

Use Case: Case-Insensitive Search

word = "Python"
user_input = "pYThOn"

if word.casefold() == user_input.casefold():
    print("Match found!")
Match found!

casefold() vs lower()

Feature lower() casefold()
Converts to lowercase Yes Yes
Suitable for international comparison No Yes
More aggressive Unicode conversion No Yes

Common Mistakes

  • Mistake: Trying to use casefold() on non-string data.
  • Solution: Always ensure the variable is a string: str(your_variable).casefold()

Interview Tip

Use casefold() when asked to perform case-insensitive string comparison in a robust and Unicode-safe way.

Summary

  • casefold() is used for case-insensitive string comparison.
  • It handles special characters better than lower().
  • Always returns a new, casefolded string.

Practice Problem

Write a function that checks if two user-entered strings are equal, ignoring case and accents.

def is_equal_case_insensitive(str1, str2):
    return str1.casefold() == str2.casefold()

# Try it!
print(is_equal_case_insensitive("Straße", "STRASSE"))

Expected Output:

True
Mallikarjuna Mallisetty, author
About the author

Mallikarjuna Mallisetty

General programming

Mallikarjuna shares practical programming tutorials and foundational concepts designed to help developers learn by building and experimenting.

View LinkedIn profile ↗