打印特殊字符

时间:2013-11-02 03:42:21

标签: python printing character percentage

如何在打印功能中打印出字符“%”。以下行失败。

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

2 个答案:

答案 0 :(得分:7)

您必须通过执行%来逃避%%。所以在你的例子中,做:

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

答案 1 :(得分:0)

考虑使用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%'

如果您的参数是字符串:

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