如何在python中打印百分比值? [英] How to print a percentage value in python?
本文介绍了如何在python中打印百分比值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的代码:
print str(float(1/3))+'%'
它显示:
0.0%
但我想得到 33%
我能做什么?
解决方案
<预><代码>>>>打印{0:.0%}".format(1./3)33%如果不想整数除法,可以从导入Python3的除法__未来__
:
this is my code:
print str(float(1/3))+'%'
and it shows:
0.0%
but I want to get 33%
What can I do?
解决方案
format
supports a percentage floating point precision type:
>>> print "{0:.0%}".format(1./3)
33%
If you don't want integer division, you can import Python3's division from __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%
这篇关于如何在python中打印百分比值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文