Print special characters

我们两清 提交于 2019-12-14 03:14:33

问题


How can I print out the character "%" in the print function. The following line fails.

print "The result is %s out of %s i.e. %d %" % (nominator, denominator, percentage)

回答1:


You must escape the % by doing %%. So in your example, do:

print "The result is %s out of %s i.e. %d %%" % (nominator, denominator, percentage)
#                                         ^ extra % to escape the one after



回答2:


Consider using format:

>>> n=23.2
>>> d=1550
>>> "The result is {:.2f} out of {:.2f} i.e. {:.2%}".format(n,d,n/d)
'The result is 23.20 out of 1550.00 i.e. 1.50%'


>>> "The result is {:,.2f} out of {:,.2f} i.e. {:.2%}".format(n,d,n/d)
'The result is 23.20 out of 1,550.00 i.e. 1.50%'

If your arguments are strings:

>>> "The result is {:,.2f} out of {} i.e. {:.2%}".format(n,str(d),n/d)
'The result is 23.20 out of 1550 i.e. 1.50%'


来源:https://stackoverflow.com/questions/19738739/print-special-characters

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