Case-insensitive string comparison

Trent Mick trentm at ActiveState.com
Mon Apr 14 15:28:34 EDT 2003


[Avner Ben wrote]
> Question:
> 
>     Does standard Python have case-insensitive string comparison and search?


You can do it by just lowercasing (or uppercasing) your strings before
searching:

    >>> s = "Blah FOO spam"
    >>> q = "Foo"
    >>> s.lower().find(q.lower())
    5


Or, if you are using regular expressions, use the IGNORECASE flag:

    >>> import re
    >>> match = re.search(q, s, re.IGNORECASE)
    >>> match.start()
    5
    >>> match.end()
    8


Cheers,
Trent

-- 
Trent Mick
TrentM at ActiveState.com





More information about the Python-list mailing list