如何在python中打印百分比值?

新手上路,请多包涵

这是我的代码:

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

它显示:

 0.0%

但我想得到 33%

我能做些什么?

原文由 zjm1126 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 553
2 个回答

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

 >>> print "{0:.0%}".format(1./3)
33%

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

 >>> 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%

原文由 miku 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于 .format() 格式方法,有一种更方便的“百分比”格式选项:

 >>> '{:.1%}'.format(1/3.0)
'33.3%'

原文由 user2489252 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题