>>>> pats = ['abcdef', 'defgef', 'effwer']
>>>> reps = ['highway', 'news', 'monitor']
>>>> s = 'defgefabcdefyuuuu\n\n\n  effwerbyuuuterrfr'
>>>> reduce(lambda x,y: x.replace(*y), zip(pats,reps), s)


The reduce() method fairly works well if you have it as a 
dictionary as well:

 >>> m = {'effwer': 'monitor', 'abcdef': 'highway', 'defgef': 'news'}
 >>> s = 'defgefabcdefyuuuu\n\n\n  effwerbyuuuterrfr'
 >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(), s)
'newshighwayyuuuu\n\n\n  monitorbyuuuterrfr'

One does get somewhat unpredictable results if one of the 
replacements contains a target search pattern (or creates it in 
the resulting string):

 >>> s = 'onetwothree'
 >>> m = {'one':'two', 'two':'three', 'three':'one'}
 >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(),s)
'twothreetwo'
 >>> m['three'] = 'four'
 >>> m['four'] = 'two'
 >>> reduce(lambda x,y: x.replace(y, m[y]), m.keys(),s)
'twothreefour'

Just a few more ideas...

-tkc



-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to