Case-insensitive string compare?

Maric Michaud maric at
Thu Sep 4 18:38:03 EDT 2008

Le Friday 05 September 2008 00:14:37 Robert Dailey, vous avez écrit :
> Hi,
> I currently have a dictionary object that I'm doing the following with:
> if lib not in stage_map:
>     # ... do stuff ...
> However, this will perform a case-sensitive comparison between lib and each
> key in stage_map. Is there a way to make this do a case-insensitive
> comparison instead? Yes, I realize I could do this:
> if lib not in [key.lower() for key in stage_map]

This is the normal python way to compare string without case, and the idiom is 
not surprising. You''ll often see for loops written like this :

for i in (e for e in iterable if predicate(e)) :

> However, I don't want to do this because it'll quickly end up getting
> messy. I want this solution to be an absolute last resort. I'm not a pro
> with python, so I'm hoping there are cleaner alternatives out there.

If you fell hard to read you can break it on two lines :

lowered_keys = (key.lower() for key in stage_map)
if lib.lower() not in lowered_keys :

BTW, it's string manipulation, it's normal it takes more than one brain cycle 
to achieve. Try the regexp solution and make your choice, more than often, I 
keep the straightforward, "read as pseudo-code", python expression.


Maric Michaud

More information about the Python-list mailing list