franco mango
franco mango

Reputation: 147

Multiple replacement for same pattern with regex

this piece of code does the replacement in a string using regex and python. With count flag you can also say how many instances to replace.

first = "33,33"
second = '22,55'
re.sub(r"\d+\,\d+", first, "There are 2,30 foo and 4,56 faa", count=1)
output: 'There are 33,33 foo and 4,56 faa'

But, how do I do multiple (different value) replace for the same pattern? I want something like:

re.sub(r"\d+\,\d+", [first,second], "There are 2,30 foo and 4,56 faa", count=2)
desired output: 'There are 33,33 foo and 22,55 faa'

Upvotes: 1

Views: 38

Answers (2)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

We can use re.sub with a callback function:

inp = "There are 2,30 foo and 4,56 faa"
repl = ["33,33", "22,55"]
output = re.sub(r'\d+,\d+', lambda m: repl.pop(0), inp)
print(output)  # There are 33,33 foo and 22,55 faa

Upvotes: 2

Andrej Kesely
Andrej Kesely

Reputation: 195613

You can use iter to do the task:

import re

first = "33,33"
second = "22,55"

i = iter([first, second])

out = re.sub(r"\d+\,\d+", lambda _: next(i), "There are 2,30 foo and 4,56 faa")
print(out)

Prints:

There are 33,33 foo and 22,55 faa

Upvotes: 1

Related Questions