How to print number with commas as thousands separators? How to print number with commas as thousands separators? python python

How to print number with commas as thousands separators?

Locale unaware

'{:,}'.format(value)  # For Python ≥2.7f'{value:,}'  # For Python ≥3.6

Locale aware

import localelocale.setlocale(locale.LC_ALL, '')  # Use '' for auto, or force e.g. to 'en_US.UTF-8''{:n}'.format(value)  # For Python ≥2.7f'{value:n}'  # For Python ≥3.6


Per Format Specification Mini-Language,

The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead.

I got this to work:

>>> import locale>>> locale.setlocale(locale.LC_ALL, 'en_US')'en_US'>>> locale.format("%d", 1255000, grouping=True)'1,255,000'

Sure, you don't need internationalization support, but it's clear, concise, and uses a built-in library.

P.S. That "%d" is the usual %-style formatter. You can have only one formatter, but it can be whatever you need in terms of field width and precision settings.

P.P.S. If you can't get locale to work, I'd suggest a modified version of Mark's answer:

def intWithCommas(x):    if type(x) not in [type(0), type(0L)]:        raise TypeError("Parameter must be an integer.")    if x < 0:        return '-' + intWithCommas(-x)    result = ''    while x >= 1000:        x, r = divmod(x, 1000)        result = ",%03d%s" % (r, result)    return "%d%s" % (x, result)

Recursion is useful for the negative case, but one recursion per comma seems a bit excessive to me.

I'm surprised that no one has mentioned that you can do this with f-strings in Python 3.6+ as easy as this:

>>> num = 10000000>>> print(f"{num:,}")10,000,000

... where the part after the colon is the format specifier. The comma is the separator character you want, so f"{num:_}" uses underscores instead of a comma. Only "," and "_" is possible to use with this method.

This is equivalent of using format(num, ",") for older versions of python 3.

This might look like magic when you see it the first time, but it's not. It's just part of the language, and something that's commonly needed enough to have a shortcut available. To read more about it, have a look at the group subcomponent.