如何使用 re.sub 替换字符 $?

huangapple go评论63阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年3月4日 02:52:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630851.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定