How can I do case insensitive string comparison in Python?
I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and Pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings.
Case-insensitive string comparison in C++ Here the logic is simple. We will convert the whole string into lowercase or uppercase strings, then compare them, and return the result. We have used the algorithm library to get the transform function to convert the string into lowercase string.
The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the i flag.
Approach No 1: Python String lower() Method This is the most popular approach to case-insensitive string comparisons in Python. The lower() method converts all the characters in a string to the lowercase, making it easier to compare two strings.
To compare strings without case sensitivity, fold the values using tolower() or toupper() . Using tolower() or toupper() or the above in either order makes no difference when looking for equality, but can make an order difference.
Assuming ASCII strings:
string1 = 'Hello' string2 = 'hello' if string1.lower() == string2.lower(): print("The strings are the same (case insensitive)") else: print("The strings are NOT the same (case insensitive)")
As of Python 3.3, casefold() is a better alternative:
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)")
If you want a more comprehensive solution that handles more complex unicode comparisons, see other answers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With