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

2024-04-24 07:49:53 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码:

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

它显示了:

0.0%

但我想得到33%

我能做什么?


Tags: 代码floatprintstr
3条回答

只是为了完整起见,因为我注意到没有人提出这种简单的方法:

>>> print("%.0f%%" % (100 * 1.0/3))
33%

详细信息:

  • %.0f代表“打印小数点后0位的浮点值”,因此%.2f将打印33.33
  • %%打印文本%。比原来干净一点+'%'
  • 1.0而不是1负责强制除法浮动,因此不再0.0

^{}支持百分比floating point precision type

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

如果不需要整数除法,可以从^{}导入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%

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

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

相关问题 更多 >