如何在python中打印百分比值? [英] How to print a percentage value in python?

查看:49
本文介绍了如何在python中打印百分比值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

print str(float(1/3))+'%'

它显示:

0.0%

但我想得到 33%

我能做什么?

解决方案

format 支持百分比浮点精度类型:

<预><代码>>>>打印{0:.0%}".format(1./3)33%

如果不想整数除法,可以从导入Python3的除法__未来__:

<预><代码>>>>来自 __future__ 进口部门>>>1/30.3333333333333333# 上面 33% 的例子现在可以在没有显式的情况下编写# 浮点数转换:>>>打印 "{0:.0f}%".format(1/3 * 100)33%# 或者更短的使用格式迷你语言:>>>打印 "{:.0%}".format(1/3)33%

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆