How to print the% sign using line formatting?

I made a small script percent calculator; however, I want to actually include "%" in the printed message ...

I tried it at the beginning - it did not work ...

oFile.write ("Percent:% s%" \ n "% percent)

Then I tried "Percentage: %s"%"\n" % percent" , which did not work.

I want the result to be as follows: Percentage: x%

I keep getting "TypeError: not all arguments converted during string formatting"

+15
python printing percentage
source share
4 answers

To print the % sign, you need to "escape" with another % sign:

 percent = 12 print "Percentage: %s %%\n" % percent # Note the double % sign >>> Percentage: 12 % 
+34
source share

Or use the format() function, which is more elegant.

 percent = 12 print "Percentage: {}%".format(percent) 

4 years later edit

Now in Python3x print() requires parentheses.

 percent = 12 print ("Percentage: {}%".format(percent)) 
+9
source share

Python 3's new approach is to use format strings.

 percent = 12 print("Percentage: {0} %\n".format(percent)) >>> Percentage: 12 % 

This is also supported in Python> 2.6.

See the docs here: Python 3 and Python 2

+3
source share

format() more elegant, but the modulo character seems faster!

http://inre.dundeemt.com/2016-01-13/string-modulo-vs-format-fight/ - shows that modulo is 30% faster!

+2
source share

All Articles