Reputation: 933
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!
Upvotes: 1
Views: 83
Reputation: 86
Use \1
instead of $1
for substitution
Check: https://regex101.com/r/T2sbD2/1
Upvotes: 1
Reputation: 78564
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:
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!
Upvotes: 5