我可以在数字中插入逗号吗?数字是字符串的一部分

时间:2017-07-19 11:33:55

标签: python regex

我想这样做。你知道一个好方法吗?

import re

if __name__ == '__main__':
    sample = "eventA 12:30 - 14:00 5200yen / eventB 15:30 - 17:00 10200yen enjoy!"
    i_want_to_generate = "eventA 12:30 - 14:00 5,200yen / eventB 15:30 - 17:00 10,200yen enjoy!"

    replaced = re.sub("(\d{1,3})(\d{3})", "$1,$2", sample)  # Wrong.
    print(replaced)  # eventA 12:30 - 14:00 $1,$2yen / eventB 15:30 - 17:00 $1,$2yen enjoy!

2 个答案:

答案 0 :(得分:5)

您没有使用正确的符号表示您的反向引用。您还可以添加包含货币的正向前瞻断言,以确保仅'yen'更改后的那些:

replaced = re.sub(r"(\d{1,3})(\d{3})(?=yen)", r"\1,\2", sample)  # Wrong.
print(replaced) 

# eventA 12:30 - 14:00 5,200yen / eventB 15:30 - 17:00 10,200yen enjoy!

答案 1 :(得分:1)

使用\1代替$1进行替换

检查:https://regex101.com/r/T2sbD2/1