-1

I'm trying to add comma separator to number string.

import re

s = '12 123 1234 12345 123456 1234567 12345678'
print(re.sub(r'(\d{3}\b)', r',\1', s))

# gives
# 12 ,123 1,234 12,345 123,456 12345,678

where:

  • 123 should'nt have comma

  • 1234567 should be 1,234,567

  • 12345678 should be 12345,678

rho
  • 771
  • 9
  • 24

1 Answers1

1

If you insist on using re:

s = '12 123 1234 12345 123456 1234567 12345678 00111222333444555666'
s2 = ''
while s != s2:
    s2 = s
    s = re.sub(r'(\d)(\d{3}\b)', r'\1,\2', s2)
print(s)

prints

12 123 1,234 12,345 123,456 1,234,567 12,345,678 00,111,222,333,444,555,666
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101