简体   繁体   English

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

[英]Can I insert comma into numbers? The numbers are parts of strings

I want to do like this. 我想这样 Do you know a good way? 你知道一个好方法吗?

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!

You're not using the correct notation for your back-reference(s). 您没有为反向引用使用正确的符号。 You could also add a positive lookahead assertion containing the currency to ensure only those after the 'yen' are changed: 您还可以添加包含货币的正向超前断言,以确保仅更改'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!

Use \\1 instead of $1 for substitution 使用\\1代替$1进行替换

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM