【发布时间】:2013-11-02 03:42:20
【问题描述】:
如何在打印功能中打印出字符“%”。以下行失败。
print "The result is %s out of %s i.e. %d %" % (nominator, denominator, percentage)
【问题讨论】:
标签: python printing character percentage
如何在打印功能中打印出字符“%”。以下行失败。
print "The result is %s out of %s i.e. %d %" % (nominator, denominator, percentage)
【问题讨论】:
标签: python printing character percentage
您必须通过 %% 转义 %。所以在你的例子中,做:
print "The result is %s out of %s i.e. %d %%" % (nominator, denominator, percentage)
# ^ extra % to escape the one after
【讨论】:
% 转义% 和`\` 撇号
考虑使用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%'
【讨论】: