如何在python中打印百分比值?
问题内容:
这是我的代码:
print str(float(1/3))+'%'
它显示:
0.0%
但我想得到 33%
我能做什么?
问题答案:
>>> print "{0:.0%}".format(1./3)
33%
如果您不希望整数除法,则可以从中导入Python3的除法__future__
:
>>> 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%