replace string patern with different value

Bill Mill bill.mill at gmail.com
Mon May 9 09:32:56 EDT 2005


On 9 May 2005 06:23:41 -0700, ajikoe at gmail.com <ajikoe at gmail.com> wrote:
> Hello,
>
> I would like to replace string with different values,
> For example :
> source = 'kode1 bla bla kode1 bla kode1'
> I have a list with each member will replace each of kode1.
> L = [11,22,33]
> So the new source will become:
> newsource = '11 bla bla 22 bla 33'
>
> How can I do it ? I tried to find using string built in function
> replace, but it will replace pattern with the same value.
>
> For this moment I think about change the string into list using
> string.split and then check one by one and replace it and then convert
> into string with addition space in the right and left of each element
> list.
>

>>> L = ['11', '22', '33']
>>> source
"xyzzy text we've got xyzzy text xyzzy yeah yeah yeah"
>>> token
'xyzzy'
>>> for rep in L:
...     source = source.replace(token, rep, 1)
...
>>> source
"11 text we've got 22 text 33 yeah yeah yeah"

And, if I may, I recommend the Python Tutorial at
http://docs.python.org/tut/tut.html .

Peace
Bill Mill
bill.mill at gmail.com



More information about the Python-list mailing list