这是我的代码:

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

它显示:

0.0%

但我想要33%

我该怎么办?


当前回答

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%

其他回答

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

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

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%

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

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

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

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

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

作为奖励,使用这里描述的很棒的字符串格式化方法: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%'

一个伟大的宝石!