Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

380
Views
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'
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Regex will work for you:

import re

def format(n):
    return re.sub(r"(\d)(?=(\d{4})+(?!\d))", r"\1,", str(n))
>>> format(12345)
'1,2345'
>>> format(12345678)
'1234,5678'
>>> format(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 ,
over 4 years ago · Santiago Trujillo Report

0

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'
over 4 years ago · Santiago Trujillo Report

0

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...

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!