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

4

5

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'
Elfredaelfrida answered 20/9, 2021 at 13:42 Comment(2)
I don't believe there are any built-in formatters for that, since that's a really weird requirement.Micromho
It's a weird requirement that is used by at least 2 billion people in the world.Richellericher
M
7

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 ,
Micromho answered 20/9, 2021 at 13:46 Comment(0)
S
3

You can break your number into chunks of 10000's using modulus and integer division, then str.join using ',' delimiters

def commas(n):
    s = []
    while n > 0:
        n, chunk = divmod(s, n)
        s.append(str(chunk))
    return ','.join(reversed(s))

>>> commas(123456789)
'1,2345,6789'
>>> commas(123)
'123'
Spivey answered 20/9, 2021 at 13:52 Comment(2)
You could use divmod to do the div and the mod in one hit.Gordy
@Gordy Good idea, updatedSpivey
C
3

Sounds like a locale thing(*). This prints 12,3456,7890 (Try it online!):

import locale

n = 1234567890

locale._override_localeconv["thousands_sep"] = ","
locale._override_localeconv["grouping"] = [4, 0]
print(locale.format_string('%d', n, grouping=True))

That's an I guess hackish way based on this answer. The other answer there talks about using babel, maybe that's a clean way to achieve it.

(*) Quick googling found this talking about Chinese grouping four digits, and OP's name seems somewhat Chinese, so...

Crore answered 20/9, 2021 at 15:31 Comment(1)
This feels like the correct answer. (This grouping is used in China, Japan, Korea, and a few other countries in Asia.)Richellericher
G
3

Using babel:

>>> from babel.numbers import format_decimal
>>> format_decimal(1234, format="#,####", locale="en")
'1234'
>>> format_decimal(12345, format="#,####", locale="en")
'1,2345'
>>> format_decimal(1234567890, format="#,####", locale="en")
'12,3456,7890'

This format syntax is specified in UNICODE LOCALE DATA MARKUP LANGUAGE (LDML). Some light bedtime reading there.

Using stdlib only (hackish):

>>> from textwrap import wrap
>>> n = 12345
>>> ",".join(wrap(str(n)[::-1], width=4))[::-1]
'1,2345'
Gordy answered 21/9, 2021 at 3:55 Comment(1)
I like this better than my answer, good suggestion!Spivey

© 2022 - 2024 — McMap. All rights reserved.