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.
For inefficiency and unreadability it's hard to beat:
Here's a one-line regex replacement:
Works only for inegral outputs:
Or for floats with less than 4 digits, change the format specifier to
%.3f
:NB: Doesn't work correctly with more than three decimal digits as it will attempt to group the decimal part:
How it works
Let's break it down:
Slightly expanding the answer of Ian Schneider:
If you want to use a custom thousands separator, the simplest solution is:
Examples
If you want the German representation like this, it gets a bit more complicated:
I prefer the locale-based solution for real projects, but I think the approach with the use of slice assignment should be mentioned here:
Gist with doctests is here - https://gist.github.com/ei-grad/b290dc761ae253af69438bbb94d82683
I'm sure there must be a standard library function for this, but it was fun to try to write it myself using recursion so here's what I came up with:
Having said that, if someone else does find a standard way to do it, you should use that instead.
from Python version 2.6 you can do this:
For Python versions < 2.6 and just for your information, here are 2 manual solutions, they turn floats to ints but negative numbers work correctly:
few things to notice here:
And a more hardcore version: