'How to replace the list of decimal numbers in a string with another list of decimal numbers?

I need to replace the list of decimal numbers in a string with another list of decimal numbers. The following is a first try, that changes all decimal numbers with the same decimal number:

>>> re.sub (r"[-+]?\d*\.\d+f?", "1.0", "hello 1.2 3.4")
'hello 1.0 1.0'

I need something like my_replace below:

>>> my_replace (r"[-+]?\d*\.\d+f?", [1.0, 2.0], "hello 1.2 3.4")
'hello 1.0 2.0'

How can i implement my_replace with python's re module?



Solution 1:[1]

I don't think that you can use a list as replacement variables and iterate over them. So it can't handle unhashable objects (this is what python is complaining about). But it wouln'd be able to handle numerics as well (so it would need a list of strings but this is obviously hypothetical xD)

I would just loop over the string and compy everything that is not a decimal number to a new string and replacing the decimal numbers found.

text = "hello 1.2 3.4 don't replace an integer: 9 but this decimal number is too much: 0.0 (so use last value!)"
new_numbers = [42, 3.1415926535]

new_text = ''
idx_last = 0
for i, tx in enumerate(re.finditer(r'[-+]?\d*\.\d+f?', text)):
    # add text before the number
    new_text += tx.string[idx_last:tx.start()]
    # add new number (but ensure that your are not overflowing the list of new numbers
    new_text += str(new_numbers[min([i, len(new_numbers) - 1])])
    # update text index
    idx_last = tx.end()
# update remaining part of the text
new_text += text[idx_last:]

"hello 42 3.1415926535 don't replace an integer: 9 but this decimal number is too much: 3.1415926535 (so use last value!)"

Wrap it to a function and you have your my_replace() =)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 max