replace string patern with different value
Fredrik Lundh
fredrik at pythonware.com
Mon May 9 09:48:14 EDT 2005
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...)
</F>
More information about the Python-list
mailing list