我制作了一个计算百分比的小脚本;但是,我希望在打印的消息中实际包含 %
...
一开始就试过了 - 没用...
oFile.write("Percentage: %s%"\n" % percent)
然后我尝试了 "Percentage: %s"%"\n"% percent"
但没有用。
我希望输出是:
Percentage: x%
我一直在努力
TypeError: not all arguments converted during string formatting
要打印 %
符号,您需要使用另一个 %
符号“转义”它:
percent = 12
print "Percentage: %s %%\n" % percent # Note the double % sign
>>> Percentage: 12 %
编辑
如今在 python3 中,一种更好(且更具可读性)的方法是使用 f-strings .请注意,其他解决方案(如下所示)也同样有效:
$python3
>>> percent = 12
>>> print(f'Percentage: {percent}%') # f-string
Percentage: 12%
>>> print('Percentage: {0}%'.format(percent)) # str format method
Percentage: 12%
>>> print('Percentage: %s%%' % percent) # older format, we 'escape' the '%' character
Percentage: 12%