[Tutor] Better Search and replace method

Kent Johnson kent37 at tds.net
Wed Mar 2 23:44:01 CET 2005

Ron Nixon wrote:
> I'm trying to figure out a better solution to do 
> multiple search and replaces in a text file without
> having to type:
> import re
> s = open('filename')
> re.sub('vaule1','value2',s)
> re.sub('vaule3','value4',s)
> etc
> I've tried putting all the vaules in a list and doing
> the replace, but came up short. Any suggestions?

See this recipe which uses the ability of re.sub() to take a callable as the substitution parameter 
to do what you want.


More information about the Tutor mailing list