Python does not have case-insensitive string replacement built into the default string class. This class provides a method that allows you to do this.
1 2 3 4 5 6 7 8 9 10 | 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)
|
Tags: text
why. Why bother with a new class just for this?
Escaping. I think you have to escape the "old" string using re.escpape to avoid problems with strings like these: "one*one=two"
I've written a new class for this purpose, mostly so that I can emulate the behaviour of the normal string.replace method (which is called on a string)
Of course, you can remove the method from the class, and it will behave exactly as it should.
Fixed.