Formate a number with commas

Chris Rebert clp2 at rebertia.com
Thu Feb 9 15:51:58 EST 2012


On Thu, Feb 9, 2012 at 12:39 PM, Peter Otten <__peter__ at web.de> wrote:
> noydb wrote:
>
>> How do you format a number to print with commas?
>>
>> Some quick searching, i came up with:
>>
>>>>> import locale
>>>>> locale.setlocale(locale.LC_ALL, "")
>>>>> locale.format('%d', 2348721, True)
>> '2,348,721'
>>
>>
>> I'm a perpetual novice, so just looking for better, slicker, more
>> proper, pythonic ways to do this.
>
>>>> import locale
>>>> locale.setlocale(locale.LC_ALL, "")
> 'de_DE.UTF-8'
>>>> "{:n}".format(1234) # locale-aware
> '1.234'
>>>> "{:,d}".format(1234) # always a comma
> '1,234'

The latter requires Python 3.1+ and is courtesy PEP 378
(http://www.python.org/dev/peps/pep-0378/ ).

Cheers,
Chris



More information about the Python-list mailing list