Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用.format()方法时,如何在{}中使用多个参数_Python_Python 3.x_Rounding_String Formatting_String.format - Fatal编程技术网

在Python中使用.format()方法时,如何在{}中使用多个参数

在Python中使用.format()方法时,如何在{}中使用多个参数,python,python-3.x,rounding,string-formatting,string.format,Python,Python 3.x,Rounding,String Formatting,String.format,我希望python中的表可以这样打印: 显然,我想使用.format()方法,但我有一个长的浮点数,看起来像这样:1464.10000000001我需要对浮点数进行舍入,这样它们看起来像这样:1464.10(总是两位小数,即使两位都是零,所以我不能使用round()函数) 我可以使用“{0.2f}”.format(“1464.10000000001”)对浮动进行取整,但是它们不会打印到nice表格中 我可以通过执行“{0:>15}.format”(“1464.10000000001”),将它们

我希望python中的表可以这样打印:

显然,我想使用.format()方法,但我有一个长的浮点数,看起来像这样:
1464.10000000001
我需要对浮点数进行舍入,这样它们看起来像这样:
1464.10
(总是两位小数,即使两位都是零,所以我不能使用round()函数)

我可以使用
“{0.2f}”.format(“1464.10000000001”)
对浮动进行取整,但是它们不会打印到nice表格中

我可以通过执行
“{0:>15}.format”(“1464.10000000001”)
,将它们放入漂亮的表格中,但它们不会四舍五入


有什么方法可以同时做到这两个方面吗?类似于
“{0:>15,.2f}.format(“1464.10000000001”)

您几乎就要做到了,只需删除逗号(并传入一个浮点数,而不是字符串):

见:

请注意,对于数字,默认对齐方式为右侧,因此可以省略

"{0:15.2f}".format(1464.1000000000001)
我总是觉得这个网站对这些东西很有用:


快到了:
“{0:>15.2f}”。格式(1464.10000000001)
可能就是你想要的。你能不能不要在
format()的内部使用
round()
大量的实用示例(在旁边)。哇,谢谢!我只是通过对.format()进行两次单独的迭代来解决这个问题,这太可怕了,这要优雅得多。我在谷歌上找不到关于这个的任何信息,所以非常感谢!
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" | "%"
fill: <empty>
align: <  # left
sign: <not specified>
width: 15
precision: 2
type: `f`
>>> "{0:>15.2f}".format(1464.1000000000001)
'        1464.10'
"{0:15.2f}".format(1464.1000000000001)