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.
If you don't want to depend on any external libraries:
This works only for non-negative integers.
For Python ≥ 2.7:
Per Format Specification Mini-Language,
I have a python 2 and python 3 version of this code. I know that the question was asked for python 2 but now (8 years later lol) people will probably be using python 3.
Python 3 Code:
Python 2 Code: (Edit. The python 2 code isn't working. I am thinking that the syntax is different).
For floats:
For ints:
I'm surprised that no one has mentioned that you can do this with f-strings in Python 3.6 as easy as this:
... where the part after the colon is the format specifier. The comma is the separator character you want, so
f"{num:_d}"
uses underscores instead of a comma.This is equivalent of using
format(num, ",d")
for older versions of python 3.The accepted answer is fine, but I actually prefer
format(number,',')
. Easier for me to interpret and remember.https://docs.python.org/3/library/functions.html#format