How to do a case-insensitive string comparison with Python?

Sometimes, we want to do a case-insensitive string comparison with Python.

In this article, we’ll look at how to do a case-insensitive string comparison with Python.

How to do a case-insensitive string comparison with Python?

To do a case-insensitive string comparison with Python, we can convert both strings we want to compare to lower case.

For instance, we write:

string1 = 'Hello'
string2 = 'hello'

if string1.casefold() == string2.casefold():
    print("The strings are the same (case insensitive)")
else:
    print("The strings are NOT the same (case insensitive)")

We call the casefold method on both strings and compare them with ==.

Therefore, we should see 'The strings are the same (case insensitive)' printed since both strings are the same ignoring the case.

Conclusion

To do a case-insensitive string comparison with Python, we can convert both strings we want to compare to lower case.