ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Case-insensitive string replacement
Submitter: Christopher Neugebauer (other recipes)
Last Updated: 2008/03/26
Version no: 1.1
Category: Text

 

Not Rated yet


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



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Wrapping template engine ...

4. Assignment in expression

5. SOLVING THE METACLASS ...

6. Povray for python

7. Calling Windows API ...

8. Generic filter logic ...

9. Function Decorators by ...

10. MS SQL Server log monitor




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.