Case insensitive replace

Adam Ernst picture Adam Ernst · May 28, 2009 · Viewed 94.4k times · Source

What's the easiest way to do a case-insensitive string replacement in Python?

Answer

Blair Conrad picture Blair Conrad · May 28, 2009

The string type doesn't support this. You're probably best off using the regular expression sub method with the re.IGNORECASE option.

>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'