Most pythonic way to format a number with commas?

Alex Martelli aleax at aleax.it
Fri Jul 12 05:12:20 EDT 2002


Emile van Sebille wrote:

> Ned Batchelder
>> For dir/ls replacement script, I wanted to format file sizes with
>> commas as a thousands separator.  I didn't find anything in the
>> standard library,
> [snip]
>> Is there one?
> 
> It's buried in locale...

"buried" is a loaded word...:-)

>>>> import locale
>>>> locale.setlocale(locale.LC_ALL, "")
> 'English_United States.1252'
>>>> locale.format("%8.2f", 1234.56)
> ' 1234.56'
>>>> locale.format("%8.2f", 1234.56,3)
> '1,234.56'

Yes, but this example risks being a BIT misleading...:

>>> import locale
>>> locale.setlocale(locale.LC_ALL, "")
'en_US'
>>> for x in range(1, 5):
...     print locale.format("%8.2f", 1234.56, x)
...
1,234.56
1,234.56
1,234.56
1,234.56
>>>

I.e., the third argument to locale.format is taken as a boolean --
if it's true, then digit grouping is performed as the locale
requires, if false or missing, no grouping.

There is, unfortunately, no "architected" way to perform
digit grouping with simply-specified number of digits and
separators -- you have to cheat.  Specifically, for example,
suppose you need digits to be grouped by-four...:

>>> locale.format("%d", 1112345673489, 1)
'1,112,345,673,489'
>>> def localeconv():
...     d = _real_localeconv()
...     d['grouping'] = [4, 4, 0]
...     return d
...
>>> _real_localeconv = locale.localeconv
>>> locale.localeconv = localeconv
>>> locale.format("%d", 1112345673489, 1)
'1,1123,4567,3489'
>>>

This works only because locale.format internally calls
locale.localeconv at a Python level -- any dependence on
internals, such as this one, is too fragile, liable to
break on any upgrade to the module involved.  Therefore
it cannot be recommended.  Unfortunately, copy-and-paste
and reinvent-the-wheel are the two recommended (sigh)
ways to "reuse" the digit-grouping functionality that's
buried (ahem) in module locale.


Alex




More information about the Python-list mailing list