|
|
 |
|
Title: Case-insensitive string replacement
Submitter: Christopher Neugebauer
(other recipes)
Last Updated: 2008/03/26
Version no: 1.1
Category:
Text
|
|
|
Description:
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.
Source: Text Source
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)
Discussion:
|
|
Add comment
|
|
Number of comments: 4
why, Not specified Not specified, 2008/03/26
Why bother with a new class just for this?
Add comment
Christopher Neugebauer, 2008/03/26
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.
Add comment
Escaping, Dirk Holtwick, 2008/03/26
I think you have to escape the "old" string using re.escpape to avoid problems with strings like these: "one*one=two"
Add comment
Christopher Neugebauer, 2008/03/26
Fixed.
Add comment
|
|
|
|
|
 |
|