How to print a percentage value in python?

How to print a percentage value in python?

format supports a percentage floating point precision type:

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

If you dont want integer division, you can import Python3s 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%

There is a way more convenient percent-formatting option for the .format() format method:

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

How to print a percentage value in python?

Just for the sake of completeness, since I noticed no one suggested this simple approach:

>>> print(%.0f%% % (100 * 1.0/3))
33%

Details:

  • %.0f stands for print a float with 0 decimal places, so %.2f would print 33.33
  • %% prints a literal %. A bit cleaner than your original +%
  • 1.0 instead of 1 takes care of coercing the division to float, so no more 0.0

Leave a Reply

Your email address will not be published. Required fields are marked *