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) 
This entry was posted in programming and tagged , . Bookmark the permalink.

3 Responses to Case-insensitive String Replacement (in Python)

  1. choor says:

    Thanks, I was looking for it :)
    Sometime i think python not better solution :(

  2. wheaties says:

    You can also do something like this:

    import re
    new_str = re.sub(‘(?i)pattern’, ‘replacement’, old_str)

    The (?i) is the magic key ;)

  3. Steve says:

    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>