How to print a percentage value in python?

zjm1126 picture zjm1126 · Mar 15, 2011 · Viewed 330.6k times · Source

this is my code:

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

and it shows:

0.0%

but I want to get 33%

What can I do?

Answer

miku picture miku · Mar 15, 2011

format supports a percentage floating point precision type:

>>> print "{0:.0%}".format(1./3)
33%

If you don't want integer division, you can import Python3's division from __future__:

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