Case insensitive 'in'

RadiantHex picture RadiantHex · Sep 2, 2010 · Viewed 122.8k times · Source

I love using the expression

if 'MICHAEL89' in USERNAMES:
    ...

where USERNAMES is a list.


Is there any way to match items with case insensitivity or do I need to use a custom method? Just wondering if there is a need to write extra code for this.

Answer

nmichaels picture nmichaels · Sep 2, 2010
username = 'MICHAEL89'
if username.upper() in (name.upper() for name in USERNAMES):
    ...

Alternatively:

if username.upper() in map(str.upper, USERNAMES):
    ...

Or, yes, you can make a custom method.