Case insensitive replace
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'
import repattern = re.compile("hello", re.IGNORECASE)pattern.sub("bye", "hello HeLLo HELLO")# 'bye bye bye'
In a single line:
import rere.sub("(?i)hello","bye", "hello HeLLo HELLO") #'bye bye bye're.sub("(?i)he\.llo","bye", "he.llo He.LLo HE.LLO") #'bye bye bye'
Or, use the optional "flags" argument:
import rere.sub("hello", "bye", "hello HeLLo HELLO", flags=re.I) #'bye bye bye're.sub("he\.llo", "bye", "he.llo He.LLo HE.LLO", flags=re.I) #'bye bye bye'