[Tutor] Better Search and replace method

Alan Gauld alan.gauld at freenet.co.uk
Wed Mar 2 23:19:45 CET 2005


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

s = open(...).read()  # I assume?

> re.sub('vaule1','value2',s)
> re.sub('vaule3','value4',s)

> I've tried putting all the vaules in a list and doing
> the replace, but came up short. Any suggestions?

Without seeing what you tried or what the results were 
I can only guess...

But did you try storing the values as a list of tuples, 
or as a dictionary?

values = [ (vaule1, value2), (vaule3,value4),...]

for target,replace in values:
   re.sub(target,replace,s)

OR

values = { 'vaule1' : 'value2',
           'vaule3' : 'value4', .....}

for target in values.keys():
   re,sub(target,values[target],s)

Finally do you need re? Or could the simple string methods work? 
They'd be slightly faster...

Alan G.


More information about the Tutor mailing list