How to Do Case-Insensitive String Comparisons in Python?

As a Python developer working on a project for one of my USA clients, I faced an issue where I needed to compare user input without considering the case, which made me explore many ways to achieve this task . In this tutorial, I will explain how to do case-insensitive string comparisons in Python with examples and screenshots of executed example code.

Case-Insensitive String Comparisons in Python

By default, string comparisons in Python are case-sensitive. This means that “Hello” and “hello” are considered different strings. In many scenarios, such as user input validation or searching for specific data, case sensitivity can lead to unexpected results.

Consider the following example:

name1 = "Sarah"
name2 = "sarah"

if name1 == name2:
    print("The names match.")
else:
    print("The names do not match.")

Output:

The names do not match.

I have executed the above example code and added the screenshot below.

Case-Insensitive String Comparisons in Python

The program will output “The names do not match” because “Sarah” and “sarah” are not identical due to the difference in capitalization.

Read How to Check if a String Ends with a Pattern in Python?

Solution 1: Convert Strings to Lower or Upper Case

One approach to perform case-insensitive string comparisons is to convert both strings to either lowercase or uppercase before comparing them. Python provides the lower() and upper() methods for this purpose.

Here’s an example:

name1 = "Michael"
name2 = "MICHAEL"

if name1.lower() == name2.lower():
    print("The names match.")
else:
    print("The names do not match.")

Output:

The names match.

I have executed the above example code and added the screenshot below.

Do Case-Insensitive String Comparisons in Python

In this case, both “Michael” and “MICHAEL” are converted to lowercase using the lower() method before the comparison. The program will output “The names match” because the lowercase versions of the strings are identical.

Check out How to Check if a String is All Uppercase in Python?

Solution 2: Using the casefold() Method

Python offers another method specifically designed for case-insensitive string comparisons: casefold(). This method returns a casefolded copy of the string, which can be used for caseless matching.

Here’s an example:

name1 = "Emily"
name2 = "eMiLy"

if name1.casefold() == name2.casefold():
    print("The names match.")
else:
    print("The names do not match.")

Output:

The names match.

I have executed the above example code and added the screenshot below.

How to Do Case-Insensitive String Comparisons in Python

The casefold() method converts both “Emily” and “eMiLy” to a common casefolded representation, allowing for case-insensitive comparison. The program will output “The names match” in this case.

Read How to Check if a String is ASCII in Python?

The Difference Between lower() and casefold()

While lower() and casefold() both convert strings to lowercase, there is a subtle difference between them. The casefold() method is more aggressive in its conversion and can handle certain edge cases better, such as the German letter “ß” (eszett).

In most cases, using either lower() or casefold() will yield the same results for case-insensitive comparisons. However, if you need to handle special characters or follow the Unicode case folding algorithm, casefold() is the recommended choice.

Read How to Check if a String is a Boolean Value in Python?

Example: Case-Insensitive User Input Validation

Let’s consider a real-world scenario where case-insensitive string comparisons are useful. Suppose you are building a program that asks users to enter their state of residence, and you want to validate the input against a list of valid states.

valid_states = ["California", "New York", "Texas", "Florida", "Illinois"]

user_state = input("Enter your state of residence: ")

if user_state.casefold() in [state.casefold() for state in valid_states]:
    print("Valid state entered.")
else:
    print("Invalid state entered.")

In this example, the user’s input is compared against the list of valid states using casefold(). By applying casefold() to both the user input and the valid states, the comparison becomes case-insensitive. So, if the user enters “california,” “CALIFORNIA,” or any other case variation, it will be considered a valid state.

Check out How to Check if a String is Base64 Encoded in Python?

Conclusion

In this tutorial, I discussed how to do case-insensitive string comparisons in Python. Python provides the lower(), upper(), and casefold() methods to facilitate such comparisons. By converting strings to a common case representation, you can perform comparisons that ignore the casing differences.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.