How do I do a case-insensitive string comparison in Python?


Have you ever encountered a situation where you needed to compare strings in Python but wanted to ignore the differences in letter casing? Worry not, for Python provides straightforward solutions to achieve case−insensitive string comparisons. In this comprehensive guide, we will explore five different code examples, each showcasing a unique method for conducting case−insensitive string comparisons. So, let's dive in and discover the wonders of Python's string comparison versatility!

Before we delve into the examples, let's briefly understand what a case−insensitive string comparison entails. When comparing strings, a case−insensitive approach treats uppercase and lowercase letters as equal, thereby disregarding the letter casing. This can be particularly useful when you want to check for equality without being concerned about the letters' cases.

Using the lower() method

Let's begin our journey by using the `lower()` method. Consider the following example:

Example

In this code, the `lower()` method is applied to both `string1` and `string2`. The `lower()` method converts all characters in the strings to lowercase. By doing so, we create a case−insensitive comparison, allowing us to check if the strings are equal without being sensitive to their letter cases. The program then prints whether the strings are equal or not in a case−insensitive manner.

string1 = "Hello, World!"
string2 = "hello, world!"

if string1.lower() == string2.lower():
    print("The strings are equal (case-insensitive).")
else:
    print("The strings are not equal (case-insensitive).")

Output

The strings are equal (case-insensitive).

Using the casefold() method

Next, let's explore the `casefold()` method, which is another excellent option for case−insensitive string comparison:

Example

In this example, we use the `casefold()` method instead of `lower()`. The `casefold()` method is similar to `lower()` but performs additional Unicode−based transformations, making it more robust for case−insensitive comparisons across different languages and special characters. The program then prints the result of the case−insensitive comparison.

string1 = "I love Python!"
string2 = "i LOVE pYTHON!"

if string1.casefold() == string2.casefold():
    print("The strings are equal (case-insensitive).")
else:
    print("The strings are not equal (case-insensitive).")

Output

The strings are equal (case-insensitive).

Using the 'str.casecmp()' function

Another method we can use is the `str.casecmp()` function. However, it requires Python 3.10 or later. Let's see how it works:

Example

Another method we can use is the `str.casecmp()` function. However, it requires Python 3.10 or later. Let's see how it works:

string1 = "Hello, Python!"
string2 = "hello, PYTHON!"

if str.casefold(string1) == str.casefold(string2):
    print("The strings are equal (case-insensitive).")
else:
    print("The strings are not equal (case-insensitive).")

Output

The strings are equal (case-insensitive).

Using 're.IGNORECASE' flag

Now, let's explore the `re.IGNORECASE` flag, which we can use in combination with regular expressions to achieve case−insensitive comparisons:

Example

In this code snippet, we use the `re.match()` function along with the `re.IGNORECASE` flag to perform a case−insensitive comparison of the two strings. The `re.IGNORECASE` flag instructs the `match()` function to ignore the differences in letter casing during the comparison. The program then prints the outcome of the case−insensitive comparison.

import re
string1 = "Python is awesome!"
string2 = "pYtHoN is aWeSoMe!"

if re.match(string1, string2, re.IGNORECASE):
    print("The strings are equal (case-insensitive).")
else:
    print("The strings are not equal (case-insensitive).")

Output

The strings are equal (case-insensitive).

Making use of 'functools.cmp_to_key()' method

Lastly, let's explore the use of custom comparison functions with the `functools.cmp_to_key()` method. This approach allows us to use any case−insensitive comparison method we desire:

Example

In this code, we define a custom comparison function `case_insensitive_compare()` that performs a case−insensitive comparison of two strings using the `lower()` method. We then utilize `functools.cmp_to_key()` to convert this function into a key function, which can be used with other comparison functions. The program then prints the result of the case−insensitive comparison.

import functools

def case_insensitive_compare(s1, s2):
    return s1.lower() == s2.lower()

string1 = "Python is fun!"
string2 = "pYtHoN iS fUn!"

if case_insensitive_compare(string1, string2):
    print("The strings are equal (case-insensitive).")
else:
    print("The strings are not equal (case-insensitive).")

Output

The strings are equal (case-insensitive).

In conclusion, Python provides multiple elegant methods to perform case−insensitive string comparisons, catering to various programming scenarios. Whether you choose to use `lower()`, `casefold()`, `str.casecmp()`, the `re.IGNORECASE` flag, or custom comparison functions with `functools.cmp_to_key()`, you can rest assured that Python's versatility empowers you to achieve your desired results effortlessly. By leveraging the examples and explanations provided in this article, you can confidently handle case−insensitive string comparisons in your Python projects, making your code more robust and inclusive.

Updated on: 08-Sep-2023

565 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements