Keller Martin Keller Martin - 1 year ago 72
Python Question

How do you use multiple arguments in {} when using the .format() method in Python

I want a table in python to print like this:

Clearly, I want to use the .format() method, but I have long floats that look like this:

I need the floats to be rounded, so that they look like this:
(always two decimal places, even if both are zeros, so I can't use the round() function).

I can round the floats using
, but then they do not print into nice tables.

I can put them into nice tables by doing
, but then they are not rounded.

Is there a way to do both? Something like

Answer Source

You were almost there, just remove the comma (and pass in a float number, not a string):


See the Format Specification Mini-Language section:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
fill        ::=  <any character>
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

Breaking the above format down then:

fill: <empty>
align: <  # left
sign: <not specified>
width: 15
precision: 2
type: `f`


>>> "{0:>15.2f}".format(1464.1000000000001)
'        1464.10'

Note that for numbers, the default alignment is to the right, so the > could be omitted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download