How to replace character $ by using re.sub?

Question:

Suppose we have the following string and list of numbers:

my_string = "We change $ to 10, $ to 22, $ to 120, $ to 230 and $ to 1000."

nums = [1, 2, 3, 4, 5]

By only using re.sub, how to replace the $ character in my_string with each of the elements in the list to have:

"We change 1 to 10, 2 to 22, 3 to 120, 4 to 230 and 5 to 1000."

When I use re.sub(r'b$', lambda i: str(nums.pop(0)), my_string), it doesn’t work and the reason is that $ is a reserved character in re.sub and according to the documentation:

Matches the end of the string or just before the newline at the end of the string …

So if I want to replace the character $ with a constant value by using re.sub, is there any solution for it?

Asked By: Bsh

||

Answers:

You can escape the $ like this:

re.sub(r'$', lambda i: str(nums.pop(0)), my_string)
Answered By: Alex
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.