How to substitute specific positions using regex and lists?

Viewed 37

lets say I have the following string in Python:

s = "Hi, I currently have 2 apples and 3 oranges"

in regex we can do

r = re.findall(r'\d',s) 

and this would give us a list containing the numbers: ["2","3"]

However, lets say I want to substitute these numbers using a list in the order that they appear in the sentence.

new_list = ["4","5"]

and make the new sentences say:

"Hi, I currently have 4 apples and 5 oranges"

I tried doing the following:

new_sentence = [re.sub(('\d'),x, s) for x in new_list]

But that gave me:

['Hi, I currently have 4 apples and 4 oranges', 'Hi, I currently have 5 apples and 5 oranges']

Which is not what I wanted. How do you substitute values using regex in the order that they appear using a list?

2 Answers

You can make an iterator from the new_list and use it in re.sub:

import re


s = "Hi, I currently have 2 apples and 3 oranges"
new_list = ["4", "5"]

new_list_iter = iter(new_list)

out = re.sub(r"\d+", lambda _: next(new_list_iter), s)
print(out)

Prints:

Hi, I currently have 4 apples and 5 oranges

Here is another solution

''.join(map( operator.add, 
             re.split('\d+', s), 
             ['4','5']+[''] 
))

When map receives multiple iterables like this, it starts by sending the first item from the two iterables as parameters to the operator.add function, and then the next two items, and so on. We have to add an empty string to the end of the replacement values to make it the same length as re.split.

Related