multiple replacements

sn smnordby at yahoo.com
Tue Jun 27 17:15:25 EDT 2000


How about using a dictionary and a loop:

replaceme = {'foo1': 'bar1', 'foo2': 'bar2', 'foo3': 'bar3'}
for key in replaceme.keys():
    srch = key
    rplc = replaceme[key]
    contents = string.replace(contents, srch, rplc)

-Steve-


siva1311 at my-deja.com wrote:

> Hi,
> I am a newbie Python programmer and was wondering the best way to make
> multiple replacements of text strings in a file. I have 10-15 strings to
> replace and right now I am doing this like:
>
>   source = open(source_file,'r')
>   contents = source.read()
>   source.close()
>
>   contents1 = string.replace(contents, 'foo1', 'bar1')
>   contents2 = string.replace(contents1, 'foo2', 'bar2')
>   ...
>   contents10 = string.replace(contents9, 'foo10', 'bar10')
>
>   dest = open(dest_file, 'w')
>   dest.write(contents10)
>   dest.close()
>
> I know this must be a terrible kludge.
>
> Using sed I can use a single statement to carry out the replacements:
>     sed "s/foo1/bar1/g
>          s/foo2/bar2/g
>          ...
>          s/foo10/bar10/g" source_file > dest_file
>
> so I assume there must be a much better method than I am currently using
> in my Python version.
>
> Any suggestions for improvement to the Python code are appreciated.
>
> -Brad
>
> Sent via Deja.com http://www.deja.com/
> Before you buy.




More information about the Python-list mailing list