[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

nonunique string replacements

Ben Racine

3/3/2010 7:06:00 AM

All,

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?

Note the whitespace is equal between the existing substring and the replacement string.

Many thanks,
Ben Racine
i3enhamin@gmail.com



2 Answers

Steven D'Aprano

3/3/2010 8:42:00 AM

0

On Tue, 02 Mar 2010 23:06:13 -0800, Ben Racine wrote:

> All,
>
> 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?

l = l.replace(" 1.", "500.2", 1)
l = l.replace(" 1.", "5.2", 1)






--
Steven

Peter Otten

3/3/2010 8:50:00 AM

0

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