Alex Rivera | Logout

Ignore case in string comparison

Asked 2012-08-16T18:24:06.487
9

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.

Edit
Report

1 Answer

21

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
answered 2012-08-16T18:28:15.783

Your Answer