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: Thelower()
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: Thecasefold()
method is similar to thelower()
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: Thestrcasecmp()
method is a built-in function in Python'sstring
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: Thecmp()
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