The Python Oracle

How to print a percentage value in python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Sunrise at the Stream

--

Chapters
00:00 Question
00:26 Accepted answer (Score 362)
00:59 Answer 2 (Score 216)
01:15 Answer 3 (Score 91)
01:57 Answer 4 (Score 79)
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/5306...

Accepted answer links:
[format]: http://docs.python.org/library/functions...
[floating point precision type]: https://www.python.org/dev/peps/pep-3101/
[__future__]: http://docs.python.org/2/library/__futur...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python2x

#avk47



ACCEPTED ANSWER

Score 413


Since Python 3.0, str.format and format support a percentage presentation type:

>>> f"{1/3:.0%}"
'33%'
>>> "{:.0%}".format(1/3)
'33%'
>>> format(1/3, ".0%")
'33%'

Percentage. Multiplies the number by 100 and displays in fixed ('f') format, followed by a percent sign.

The .0 part of the format spec .0% indicates that you want zero digits of precision after the decimal point, because with f"{1/3:%}" you would get the string '33.333333%'.

It works with integers, floats, and decimals. See PEP 3101.




ANSWER 2

Score 223


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

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



ANSWER 3

Score 94


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



ANSWER 4

Score 42


You are dividing integers then converting to float. Divide by floats instead.

As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language

To specify a percent conversion and precision.

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

A great gem!