mutliple search and replace

Bengt Richter bokr at oz.net
Wed Mar 27 23:53:02 EST 2002


On Wed, 27 Mar 2002 18:13:48 -0800, "Emile van Sebille" <emile at fenx.com> wrote:

>Trung Hoang
>> Suppose i have a map (or two lists). is it possible to make a sweep
>through
>> a string to find all occurances of key's in the map then replace them
>all in
>> one sweep?
>>
>
>>>> d = {'one':'een','two':'twee','three':'drie','four':'vier'}
>>>> s = "one two buckle my shoe three four je t'adore"
>>>> ' '.join([d.get(w,w) for w in s.split()])
>"een twee buckle my shoe drie vier je t'adore"
>
>
Nice. Here's a variant that doesn't use delimiters or
modify white space (key order could make a difference,
depending on key overlap):

 >>> import re
 >>> d = {'one':'een','two':'twee','three':'drie','four':'vier'}
 >>> resp = re.compile('('+'|'.join(d.keys())+')')
 >>> s = "one two buckle my shoe three four je t'adore"
 >>> ''.join([d.get(w,w) for w in resp.split(s)])
 "een twee buckle my shoe drie vier je t'adore"
 >>> s = "one.two+buckle_my_shoe,three-four&je_t'adore"
 >>> ''.join([d.get(w,w) for w in resp.split(s)])
 "een.twee+buckle_my_shoe,drie-vier&je_t'adore"

Regards,
Bengt Richter



More information about the Python-list mailing list