Reputation: 735
For example, I've got a string like:
'blah blah 1.344 blah 1.455'
and a list like:
[2.888, 4.033]
I know that the string and the list contain an equal quantity of numbers and want to replace all the numbers in the string with the numbers from the list using regex. I want something like:
re.sub('\d\.\d+', list[i], line)
but don't know how to make it replace each match with the next item from list, not just the same item. I want to preserve all of the text and all of the whitespace exactly the same, so splitting to a list, replacing by index and joining back seems not to be the thing I need.
Upvotes: 4
Views: 4261
Reputation: 122086
The second repl
parameter to re.sub
can be an arbitrary function that takes a single match
object and returns a string to replace it. In your case:
>>> import re
>>> repl = [2.888, 4.033]
>>> re.sub(
r'\d\.\d+', # note raw string to avoid issues with backslashes
lambda match: str(repl.pop(0)), # replace each match with the next item in the list
'blah blah 1.344 blah 1.455'
)
'blah blah 2.888 blah 4.033'
Upvotes: 7
Reputation: 4951
you can simply do:
>>> re.sub('\d\.\d+', '{}', line).format(*list)
'blah blah 2.888 blah 4.033'
(I used list
as a variable name because in your question you used it, however, this is a VERY bad idea to override the list
keyword)
Upvotes: 3
Reputation: 67978
def repl(matchobj):
return str(y.pop(0))
x='blah blah 1.344 blah 1.455'
y=[2.888, 4.033]
print re.sub(r"\d+\.\d+",repl,x)
You can simply create a replace funtion in re.sub
Upvotes: 2