nonunique string replacements

B

Ben Racine

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
(e-mail address removed)
 
S

Steven D'Aprano

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)
 
P

Peter Otten

Ben said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top