Welcome, guest | Sign In | My Account | Store | Cart
NOTE: Recipes have moved! Please visit GitHub.com/activestate/code for the current versions.

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, 10 lines
 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)

4 comments

sjf 10 years, 1 month ago  # | flag

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

Dirk Holtwick 10 years ago  # | flag

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.

Created by Christopher Neugebauer on Wed, 26 Mar 2008 (PSF)
Python recipes (4591)
Christopher Neugebauer's recipes (1)

Required Modules

Other Information and Tasks