这是我的代码:

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

它显示:

0.0%

但我想要33%

我该怎么办?


当前回答

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

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

其他回答

那么你应该这样做:

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

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

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%

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

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

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

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

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

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