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

这是我的代码:

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

它显示:

0.0%

但是我想要得到33%

我该怎么办?

463391 次浏览

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%

你将整数除法然后转换为浮点数。而是除以浮点数。

作为奖励,使用这里描述的很棒的字符串格式化方法:http://docs.python.org/library/string.html#format-specification-mini-language

指定一个百分比的转换和精度。

>>> float(1) / float(3)
[Out] 0.33333333333333331


>>> 1.0/3.0
[Out] 0.33333333333333331


>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'


>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'

一个伟大的宝石!

那么你应该这样做:

print str(int(1.0/3.0*100))+'%'

.0将它们表示为浮点数,然后int()将它们舍入为整数。

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

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

细节:

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

对于.format()格式方法,有一个更方便的'percent'格式化选项:

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

只需添加python3 f-string解决方案

prob = 1.0/3.0
print(f"{prob:.0%}")

我用这个

ratio = round(1/3, 2)
print(f"{ratio} %")


output: 0.33 %

这就是我让它工作的方法,像魔法一样

divideing = a / b
percentage = divideing * 100
print(str(float(percentage))+"%")