In Python, how can I do multiple formats at once:
So I want to make a number have no decimal places and have a thousands separator:
num = 80000.00
I want it to be 80,000
I know I can do these two things serepatly, but how would I combine them:
"{:,}".format(num) # this will give me the thousands separator
"{0:.0f}".format(num) # this will give me only two decimal places
So is it possible to combine these together??
You can combine the two format strings. The comma goes first after the colon:
Note that you can also use the free
format()function instead of the methodstr.format()when formatting only a single value:Edit: The
,to include a thousands separator was introduced in Python 2.7, so the above conversions don’t work in Python 2.6. In that version you will need to roll your own string formatting. Some ad-hoc code: