Format thousands in Python

01 February 2019   2 comments   Python

tl;dr; Use f"{number:,}" to thousands format an integer to a string.

I keep forgetting and having to look this up every time. Hopefully by blogging about it, this time it'll stick in my memory. And hopefully in yours too :)

Suppose you have a number, like 1234567890 and you want to display it, here's how you do it:

>>> number = 1234567890
>>> f"{number:,}"

In the past, before Python 3.6, I've been using:

>>> number = 1234567890
>>> format(number, ",")

All of this and more detail can be found in PEP 378 -- Format Specifier for Thousands Separator. For example, you can do this beast too:

>>> number = 1234567890
>>> f"{number:020,.2f}"

which demonstrates (1) how to do zero-padding (of length 20), (2) the thousands comma, (3) round to 2 significant figures. All useful weapons to be able to draw from the top of your head.


Also, incredibly useful is the equivalent of somestring.ljust(10):

>>> mystr = "peter"
>>> f"{mystr:10}"
'peter     '
>>> f"{mystr:>10}"
'     peter'


John S.

You can also format numbers with an underscore separator instead of commas (`format(number, '_')`). That has the advantage of being both quickly human-eye-parsable AND python parsable, e.g. you can copy and paste the output right back into the REPL (and quite a few other languages also understand numbers with underscore separators).

Also, since the variable *named* underscore is the last result shown in the REPL, you can reformat the last output with underscore separators by typing `f"{_:_}"`, which is silly and confusing syntax but often pretty convenient.

Peter Bengtsson

Cheers! This is a good point. Practical.

Your email will never ever be published

Related posts

hashin 0.14.5 and canonical pip hashes 31 January 2019
Displaying fetch() errors and unwanted responses in React 06 February 2019
Related by Keyword:
Format numbers with numberWithCommas() or Number.toLocaleString() 05 March 2019
Credit Card formatter in Javascript 19 November 2013
Fastest way to thousands-commafy large numbers in Python/PyPy 13 October 2012
jsonpprint - a Python script to format JSON data nicely 21 November 2010