nonunique string replacements

Peter Otten __peter__ at web.de
Wed Mar 3 03:49:38 EST 2010


Ben Racine wrote:

> Say I have a string "l" ...
> 
> l = 'PBUSH     201005       K      1.      1.      1.      1.      1.     
> 1.'
> 
> And I want to replace the first "   1." with a "500.2" and the second " 
> 1." with " 5.2" ...
> 
> What pythonic means would you all recommend?

With regular expressions:

>>> import re
>>> replacements = iter(["one", "two", "three"])
>>> re.compile("replaceme").sub(lambda m: next(replacements), "foo replaceme 
bar replaceme baz replaceme bang")
'foo one bar two baz three bang'

With string methods:

>>> replacements = iter(["", "one", "two", "three"])
>>> "".join(a + b for a, b in zip(replacements, "foo replaceme bar replaceme 
baz replaceme bang".split("replaceme")))
'foo one bar two baz three bang'

Peter



More information about the Python-list mailing list