Ignore case in string comparison

2019-02-21 18:26发布

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.

标签: python equals
3条回答
你好瞎i
2楼-- · 2019-02-21 19:03

How about this, without isinstance (frowned upon):

def equal(a, b):
    try:
        return a.lower() == b.lower()
    except AttributeError:
        return a == b
查看更多
干净又极端
3楼-- · 2019-02-21 19:25

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
查看更多
Ridiculous、
4楼-- · 2019-02-21 19:27
>>> def equals_ignore_case(a,b):
...   return a.upper() == b.upper()
...
>>> equals_ignore_case("hello","Hello")
True
查看更多
登录 后发表回答