printf("%%"); Or you could use ASCII code and write: printf("%c", 37);
The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value. The following Python code illustrates the way of performing string formatting.
Answer. In Python, string formatters are essentially placeholders that let us pass in different values into some formatted string. The %d formatter is used to input decimal values, or whole numbers. If you provide a float value, it will convert it to a whole number, by truncating the values after the decimal point.
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%
There is a way more convenient 'percent'-formatting option for the .format()
format method:
>>> '{:.1%}'.format(1/3.0)
'33.3%'
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
Just to add Python 3 f-string solution
prob = 1.0/3.0
print(f"{prob:.0%}")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With