How do I print a '%' sign using string formatting?

家住魔仙堡 提交于 2019-12-05 10:05:15

问题


I've made a little script to calculator percent; however, I wish to actually include the '%' within the message printed...

Tried this at the start - didn't work...

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

I then tried "Percentage: %s"%"\n" % percent" which didn't work.

I'd like the output to be: Percentage: x%

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


回答1:


To print the % sign you need to 'escape' it with another % sign:

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



回答2:


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

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

4 years later edit

Now In Python3x print() requires parenthesis.

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



回答3:


The new Python 3 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




回答4:


format() is more elegant but the modulo sign seems to be quicker!

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



来源:https://stackoverflow.com/questions/28343745/how-do-i-print-a-sign-using-string-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!