英文:
How to replace character $ by using re.sub?
问题
假设我们有以下字符串和数字列表:
my_string = ""We change $ to 10, $ to 22, $ to 120, $ to 230 and $ to 1000.""
nums = [1, 2, 3, 4, 5]
只使用re.sub,如何将my_string中的$字符替换为列表中的每个元素,得到以下结果:
""We change 1 to 10, 2 to 22, 3 to 120, 4 to 230, and 5 to 1000.""
当我使用re.sub(r'\b$', lambda i: str(nums.pop(0)), my_string)时,它不起作用,原因是$是re.sub中的保留字符,根据文档的说法:
匹配字符串的末尾或字符串末尾的换行符之前...
因此,如果我想使用re.sub将字符$替换为常量值,是否有任何解决方案?
英文:
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?
答案1
得分: 2
你可以这样转义 $:
re.sub(r'$', lambda i: str(nums.pop(0)), my_string)
英文:
You can escape the $ like this:
re.sub(r'$', lambda i: str(nums.pop(0)), my_string)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论