我正在尝试打印一些东西:
>>> print "%02i,%02i,%02g" % (3, 4, 5.66)
03,04,5.66
然而,这是不正确的。如果您注意到,可以正确地将零添加到所有整数浮点(前两个数字)。我需要它,如果小数点左边有一个数字,那么就会有一个前导零。
也就是说,上面的解决方案应该返回:
03,04,05.66
我做错了什么?
发布于 2016-09-14 05:22:58
对于g
,请指定和宽度和精度:
>>> print "%02i,%02i,%05.3g" % (3, 4, 5.66)
03,04,05.66
F与g
f
和g
之间的区别如下所示:
>>> print "%07.1f, %07.1f, %07.1f" % (1.23, 4567.8, 9012345678.2)
00001.2, 04567.8, 9012345678.2
>>> print "%07.1g, %07.1g, %07.1g" % (1.23, 4567.8, 9012345678.2)
0000001, 005e+03, 009e+09
当给定较大的数字时,g
会切换到科学记数法,而f
只是使用更多的空格。
类似地,当需要时,对于较小的数字,g
会切换到科学记数法:
>>> print "%07.1f, %07.1f, %07.1f" % (.01, .0001, .000001)
00000.0, 00000.0, 00000.0
>>> print "%07.1g, %07.1g, %07.1g" % (.01, .0001, .000001)
0000.01, 00.0001, 001e-06
发布于 2016-09-14 05:22:57
格式%02g
指定的最小宽度为2。您可以使用%0m.n
语法,其中m
是最小宽度,n
是小数位数。您需要的是:
>>> print "%02i,%02i,%05.2f" % (3, 4, 5.66)
03,04,05.66
发布于 2016-09-14 05:22:57
使用不同的格式,如f
print "%02i,%02i,%05.2f" % (3, 4, 5.66)
^^^^^^
或使用g
print "%02i,%02i,%05.3g" % (3, 4, 5.66)
^^^^^^
但我会坚持使用f
。我猜这就是您在这里要做的(g
有时可以使用十进制格式)。更多信息请点击此处:formatting strings with %
'f' Floating point decimal format.
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4 or not less than precision, decimal format otherwise.
https://stackoverflow.com/questions/39482902
复制相似问题