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.
Just subclass
long
(orfloat
, or whatever). This is highly practical, because this way you can still use your numbers in math ops (and therefore existing code), but they will all print nicely in your terminal.This is what I do for floats. Although, honestly, I'm not sure which versions it works for - I'm using 2.7:
Returns: 4,385,893.38
Update: I recently had an issue with this format (couldn't tell you the exact reason), but was able to fix it by dropping the
0
:Here's one that works for floats too:
Usage Example:
One liner for Python 2.5+ and Python 3 (positive int only):
I am a Python beginner, but an experienced programmer. I have Python 3.5, so I can just use the comma, but this is nonetheless an interesting programming exercise. Consider the case of an unsigned integer. The most readable Python program for adding thousands separators appears to be:
It is also possible to use a list comprehension:
This is shorter, and could be a one liner, but you will have to do some mental gymnastics to understand why it works. In both cases we get:
The first version is the more sensible choice, if you want the program to be understood.
I'm using python 2.5 so I don't have access to the built-in formatting.
I looked at the Django code intcomma (intcomma_recurs in code below) and realized it's inefficient, because it's recursive and also compiling the regex on every run is not a good thing either. This is not necessary an 'issue' as django isn't really THAT focused on this kind of low-level performance. Also, I was expecting a factor of 10 difference in performance, but it's only 3 times slower.
Out of curiosity I implemented a few versions of intcomma to see what the performance advantages are when using regex. My test data concludes a slight advantage for this task, but surprisingly not much at all.
I also was pleased to see what I suspected: using the reverse xrange approach is unnecessary in the no-regex case, but it does make the code look slightly better at the cost of ~10% performance.
Also, I assume what you're passing in is a string and looks somewhat like a number. Results undetermined otherwise.
And here are the test results: