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

这是我的代码:

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

它显示:

0.0%

但我想得到 33%

我能做什么?

最佳答案

format支持百分比floating point precision type :

>>> 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%

https://stackoverflow.com/questions/5306756/

相关文章:

linux - 使用 find 命令但排除两个目录中的文件

python - 访问对象内存地址

python - 在 Python 中使用多个参数进行字符串格式化(例如 '%s ... %s' )

linux - 如何使用 cURL 从 GitHub 下载 tarball?

windows - 如何确定特定文件是否在 Windows 中打开?

python - 仅在 Django 启动 ONCE 时执行代码?

python - linux tee 不能与 python 一起使用?

python - Python 的 List 是如何实现的?

python - 如何在被调用的方法中获取调用者的方法名?

linux - 使用 bash 为文件添加文件扩展名