I am trying to print an integer in Python 2.6.1 with commas as thousands separators. For example, I want to show the number 1234567
as 1,234,567
. How would I go about doing this? I have seen many examples on Google, but I am looking for the simplest practical way.
It does not need to be locale-specific to decide between periods and commas. I would prefer something as simple as reasonably possible.
From the comments to activestate recipe 498181 I reworked this:
It uses the regular expressions feature: lookahead i.e.
(?=\d)
to make sure only groups of three digits that have a digit 'after' them get a comma. I say 'after' because the string is reverse at this point.[::-1]
just reverses a string.Python 3
--
Integers (without decimal):
"{:,d}".format(1234567)
--
Floats (with decimal):
"{:,.2f}".format(1234567)
where the number before
f
specifies the number of decimal places.--
Bonus
Quick-and-dirty starter function for the Indian lakhs/crores numbering system (12,34,567):
https://stackoverflow.com/a/44832241/4928578
I got this to work:
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:Recursion is useful for the negative case, but one recursion per comma seems a bit excessive to me.
Here is the locale grouping code after removing irrelevant parts and cleaning it up a little:
(The following only works for integers)
There are already some good answers in here. I just want to add this for future reference. In python 2.7 there is going to be a format specifier for thousands separator. According to python docs it works like this
In python3.1 you can do the same thing like this:
You can also use
'{:n}'.format( value )
for a locale representation. I think this is the simpliest way for a locale solution.For more information, search for
thousands
in Python DOC.For currency, you can use
locale.currency
, setting the flaggrouping
:Code
Output
This does money along with the commas