How do I do a case-insensitive string comparison?
You can convert both strings to lowercase or uppercase (using the lower()
or upper()
method) before doing the comparison.
Python code snippet for case-insensitive string comparison:
string1 = "Hello World"
string2 = "HELLO WORLD"
if string1.lower() == string2.lower():
print("The strings are case-insensitively equal.")
else:
print("The strings are not case-insensitively equal.")
Watch a video course
Python - The Practical Guide
or
string1 = "Hello World"
string2 = "HELLO WORLD"
if string1.upper() == string2.upper():
print("The strings are case-insensitively equal.")
else:
print("The strings are not case-insensitively equal.")
In this example, the comparison will be true and the message "The strings are case-insensitively equal." will be printed.