Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: 1464.1000000000001 I need the floats to be rounded, so that they look like this: 1464.10 (always two decimal places, even if both are zeros, so I can't use the round() function).

I can round the floats using "{0:.2f}".format("1464.1000000000001"), but then they do not print into nice tables.

I can put them into nice tables by doing "{0:>15}.format("1464.1000000000001"), but then they are not rounded.

Is there a way to do both? Something like "{0:>15,.2f}.format("1464.1000000000001")?

like image 244
Keller Martin Avatar asked Dec 14 '22 03:12

Keller Martin


2 Answers

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

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

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`

Demo:

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

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

like image 116
Martijn Pieters Avatar answered May 10 '23 01:05

Martijn Pieters


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

I always find this site useful for this stuff:

https://pyformat.info/

like image 39
B. Eckles Avatar answered May 10 '23 01:05

B. Eckles