Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do a case-insensitive string comparison?

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.

like image 678
Kozyarchuk Avatar asked Nov 26 '08 01:11

Kozyarchuk


People also ask

How do you do case-insensitive string comparison in C++?

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.

Which will do case-insensitive comparison of string contents?

The best way to do a case insensitive comparison in JavaScript is to use RegExp match() method with the i flag.

How do you make a comparison case-insensitive in Python?

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.

How do I find a string without case sensitive?

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.


1 Answers

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.

like image 67
Harley Holcombe Avatar answered Sep 30 '22 22:09

Harley Holcombe