trouble with replace

Tim Chase python.list at tim.thechases.com
Sat Aug 12 17:53:48 EDT 2006


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






More information about the Python-list mailing list