Case-insensitive string comparison in Python


In Python, there are multiple methods to perform case-insensitive string comparison. Here are some of them:

  • Using the lower() method: The lower() method converts all the characters in a string to lowercase. We can use this method to convert both the strings to lowercase and then compare them.

Example:

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

if string1.lower() == string2.lower():
    print("Strings are equal")
else:
    print("Strings are not equal")

Output:

Strings are equal
  • Using the casefold() method: The casefold() method is similar to the lower() method, but it is more aggressive in its conversion. It converts more characters to their lowercase equivalent, which makes it more suitable for case-insensitive comparisons.

Example:

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

if string1.casefold() == string2.casefold():
    print("Strings are equal")
else:
    print("Strings are not equal")

Output:

Strings are equal
  • Using the strcasecmp() method: The strcasecmp() method is a built-in function in Python's string module. It performs a case-insensitive comparison of two strings and returns 0 if they are equal.

Example:

import string

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

if string.strcasecmp(string1, string2) == 0:
    print("Strings are equal")
else:
    print("Strings are not equal")

Output:

Strings are equal
  • Using the cmp() method: The cmp() method is a built-in function in Python 2.x. It compares two strings and returns 0 if they are equal. However, it is not available in Python 3.x.

Example:

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

if cmp(string1.lower(), string2.lower()) == 0:
    print("Strings are equal")
else:
    print("Strings are not equal")

Output:

Strings are equal


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.