Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a number with comma every four digits in Python?

I have a number 12345 and I want the result '1,2345'. I tried the following code, but failed:

>>> n = 12345
>>> f"{n:,}"
'12,345'
like image 204
Jerry Chou Avatar asked Dec 22 '22 15:12

Jerry Chou


1 Answers

Regex will work for you:

import re


def format_number(n):
    return re.sub(r"(\d)(?=(\d{4})+(?!\d))", r"\1,", str(n))
>>> format_number(123)
'123'
>>> format_number(12345)
'1,2345'
>>> format_number(12345678)
'1234,5678'
>>> format_number(123456789)
'1,2345,6789'

Explanation:

Match:

  • (\d) Match a digit...
  • (?=(\d{4})+(?!\d)) ...that is followed by one or more groups of exactly 4 digits.

Replace:

  • \1, Replace the matched digit with itself and a ,
like image 177
ruohola Avatar answered Dec 27 '22 10:12

ruohola