Case-insensitive String Replacement (in Python)

One feature that Python’s built-in string replacement facilities does not provide is case-insensitive string replacement. This is a reasonably useful construct (that I use fairly frequently in other languages, such as PHP), which I couldn’t find code for after Googling — so here’s some code that does it (licenced under the WTFPL, of course)

 import re def ireplace(self,old,new,count=0): ''' Behaves like string.replace(), but does so in a case-insensitive fashion. ''' pattern = re.compile(re.escape(old),re.I) return re.sub(pattern,new,self,count) 

You can also subclass str in order to use it as a bound method:

 import re class str_cir(str): ''' A string with a built-in case-insensitive replacement method ''' def ireplace(self,old,new,count=0): ''' Behaves like S.replace(), but does so in a case-insensitive fashion. ''' pattern = re.compile(re.escape(old),re.I) return re.sub(pattern,new,self,count) 

3 thoughts on “Case-insensitive String Replacement (in Python)

  1. Hey thanks a lot the “(?i)EN” helped me replace only strings that were Upper Case EN and not lower case :)

    awesome

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>