>>> from __future__ import division
>>> 1 / 3
0.3333333333333333
# The above 33% example would could now be written without the explicit
# float conversion:
>>> print "{0:.0f}%".format(1/3 * 100)
33%
# Or even shorter using the format mini language:
>>> print "{:.0%}".format(1/3)
33%
只是为了完整起见,因为我注意到没有人提出这种简单的方法:
详细信息:
%.0f
代表“打印小数点后0位的浮点值”,因此%.2f
将打印33.33
%%
打印文本%
。比原来干净一点+'%'
1.0
而不是1
负责强制除法浮动,因此不再0.0
^{} 支持百分比floating point precision type:
如果不需要整数除法,可以从^{} 导入Python3的除法:
对于
.format()
格式方法,有一种更方便的“百分比”格式选项:相关问题 更多 >
编程相关推荐