replace string patern with different value
Bengt Richter
bokr at oz.net
Mon May 9 19:53:17 EDT 2005
On Mon, 9 May 2005 15:48:14 +0200, "Fredrik Lundh" <fredrik at pythonware.com> wrote:
>Bill Mill wrote:
>
>>>>> for rep in L:
>> ... source = source.replace(token, rep, 1)
>
>here's another way to do it:
>
>>>> L = ["11", "22", "33"]
>>>> S = "xyzzy text we've got xyzzy text xyzzy yeah yeah yeah"
>>>> L.reverse()
>>>> re.sub("xyzzy", lambda x: L.pop(), S)
>"11 text we've got 22 text 33 yeah yeah yeah"
>
>or, less destructive:
>
>>>> L = ["11", "22", "33"]
>>>> S = "xyzzy text we've got xyzzy text xyzzy yeah yeah yeah"
>>>> re.sub("xyzzy", lambda x, pop=iter(L).next: pop(), S)
>
>(a few more iterations of this idea and we're in python riddle country...)
>
Another:
>>> L = ["11", "22", "33"]
>>> S = "xyzzy text we've got xyzzy text xyzzy yeah yeah yeah"
>>> ''.join([(i%2 and [n()] or [s()])[0] for s, n in
... [(iter(S.split('xyzzy')).next, iter(L).next)] for i in xrange(2*len(L)+1)])
"11 text we've got 22 text 33 yeah yeah yeah"
Or maybe:
>>> ''.join(map(lambda x,y:(x or '')+(y or ''), S.split('xyzzy'), L))
"11 text we've got 22 text 33 yeah yeah yeah"
Regards,
Bengt Richter
More information about the Python-list
mailing list