Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple format options in Python

Tags:

python

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??

like image 771
Christopher H Avatar asked Dec 26 '22 20:12

Christopher H


1 Answers

You can combine the two format strings. The comma goes first after the colon:

>>> "{:,.0f}".format(80000.0)
'80,000'

Note that you can also use the free format() function instead of the method str.format() when formatting only a single value:

>>> format(80000.0, ",.0f")
'80,000'

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:

def format_with_commas(x):
    s = format(x, ".0f")
    j = len(s) % 3
    if j:
         groups = [s[:j]]
    else:
         groups = []
    groups.extend(s[i:i + 3] for i in range(j, len(s), 3))
    return ",".join(groups)
like image 178
Sven Marnach Avatar answered Jan 11 '23 22:01

Sven Marnach