Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignore case in string comparison

Tags:

python

equals

If I have two variables, a and b and they could be integers, float, or strings.

I want to return True if they are equal (in case of string, ignore case).

As Pythonic as possible.

like image 518
user1008636 Avatar asked Aug 16 '12 18:08

user1008636


People also ask

How do you make a string case insensitive?

Java String equalsIgnoreCase() method Java equalsIgnoreCase() method is used to check equal strings in case-insensitive manner.

How do you ignore a case in a string 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 you make a string case insensitive in C #?

Use the Equals() method to compare strings case-insensitive using StringComparison parameter.

How do you compare two strings to ignore spaces in Python?

Use str. casefold() to compare two string ignoring the case. Trim strings using native methods or regex to ignore whitespaces when performing string comparison.


1 Answers

This is the most pythonic I can think of. Better to ask for foregiveness than for permission:

>>> def iequal(a, b):
...    try:
...       return a.upper() == b.upper()
...    except AttributeError:
...       return a == b
... 
>>> 
>>> iequal(2, 2)
True
>>> iequal(4, 2)
False
>>> iequal("joe", "Joe")
True
>>> iequal("joe", "Joel")
False
like image 57
jterrace Avatar answered Oct 22 '22 18:10

jterrace