Skip to content

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:

Convert strings to lowercase with lower() method in Python

python
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.")

<div class="alert alert-info flex not-prose"> Watch a course Python - The Practical Guide</div>

or

Convert strings to uppercase with upper() method in Python

python
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.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.