Ignore case in string comparison

耗尽温柔 提交于 2019-12-01 15:54:11

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

How about this, without isinstance (frowned upon):

def equal(a, b):
    try:
        return a.lower() == b.lower()
    except AttributeError:
        return a == b
>>> def equals_ignore_case(a,b):
...   return a.upper() == b.upper()
...
>>> equals_ignore_case("hello","Hello")
True
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!