如何在python中显示百分比

zjm*_*126 160 python python-2.x

这是我的代码:

print str(float(1/3))+'%'
Run Code Online (Sandbox Code Playgroud)

它显示:

0.0%
Run Code Online (Sandbox Code Playgroud)

但我想得到 33%

我能做什么.

mik*_*iku 246

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

>>> print "{0:.0%}".format(1./3)
33%
Run Code Online (Sandbox Code Playgroud)

如果您不想进行整数除法,可以从__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%
Run Code Online (Sandbox Code Playgroud)

  • 在Python 2中,我使用`1.0`而不是`float(1)`或`1.`.恕我直言,它不像前者那么突兀,也不像后者那样微妙. (14认同)
  • `float(1)`比`1.`真的更pythonic? (4认同)

小智 165

格式化方法有一种更方便的'百分比'格式化选项.format():

>>> '{:.1%}'.format(1/3.0)
'33.3%'
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案,因为它不需要乘以100.相反,它利用了`format`已经知道如何打印百分比的事实! (12认同)
  • 这应该是公认的答案.这更像Pythonic,使用内置功能来消除乘以100的无意义的实现细节. (5认同)
  • 有没有办法用旧学校"%.1f"格式化? (4认同)
  • 呵呵,没有.没有实际的%格式化类型. (3认同)
  • 所以在 f-string 样式中它将是 `f"{1/3.0:.1%}"` (3认同)
  • 有点“不太方便”,但是,是的!就像上面建议的 `print("%.1f%%" % (100 * 1.0/3))` (2认同)

Mes*_*ion 61

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

>>> print("%.0f%%" % (100 * 1.0/3))
33%
Run Code Online (Sandbox Code Playgroud)

细节:

  • %.0f代表" 打印带小数点后0位的浮点数 ",因此%.2f会打印33.33
  • %%打印文字%.比你原来的一点清洁+'%'
  • 1.0而不是1照顾强迫分裂浮动,所以不再0.0

  • 请原谅,@ RuggeroTurra?从广义上讲,此_is_格式转换为将输入显示为字符串的形式。请注意,OP从来不需要使用`.format()`,并且`%`格式(在Python中也称为_string插值_)是完全有效的替代方法。 (2认同)

men*_*rfa 45

只是为了添加 Python 3 f-string 解决方案

prob = 1.0/3.0
print(f"{prob:.0%}")
Run Code Online (Sandbox Code Playgroud)

  • @MichalK 不,不应该。当您的数字是分数时,您需要使用 f"{prob:.0%}" 自动转换为百分比。 (5认同)
  • @FM https://docs.python.org/3.9/library/string.html#format-string-syntax (2认同)

Yuj*_*ita 36

你正在划分整数然后转换为浮点数.除以花车代替.

作为奖励,使用这里描述的令人敬畏的字符串格式化方法: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%'
Run Code Online (Sandbox Code Playgroud)

一个伟大的宝石!


Mor*_*sen 5

那么你会想要这样做:

print str(int(1.0/3.0*100))+'%'
Run Code Online (Sandbox Code Playgroud)

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