ActiveState Code

Recipe 552726: Case-insensitive string replacement


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.

Python
 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)

Comments

  1. 1. At 8:09 a.m. on 26 mar 2008, Anonymous said:

    why. Why bother with a new class just for this?

  2. 2. At 12:13 p.m. on 26 mar 2008, Dirk Holtwick said:

    Escaping. I think you have to escape the "old" string using re.escpape to avoid problems with strings like these: "one*one=two"

  3. 3. At 2:25 p.m. on 26 mar 2008, Christopher Neugebauer (the author) said:

    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.

  4. 4. At 2:25 p.m. on 26 mar 2008, Christopher Neugebauer (the author) said:

    Fixed.

Sign in to comment