2024-05-23 17:00:19 发布
网友
我为计算器百分比编写了一个小脚本;但是,我希望在打印的消息中包含“%”。。。
刚开始试过-没用。。。
oFile.write("Percentage: %s%"\n" % percent)
然后我尝试了"Percentage: %s"%"\n" % percent",但没有成功。
"Percentage: %s"%"\n" % percent"
我希望输出为:百分比:x%
我一直得到“TypeError:不是所有参数都在字符串格式化期间转换”
要打印%符号,需要用另一个%符号“转义”:
%
percent = 12 print "Percentage: %s %%\n" % percent # Note the double % sign >>> Percentage: 12 %
新的Python 3方法是使用格式字符串。
percent = 12 print("Percentage: {0} %\n".format(percent)) >>> Percentage: 12 %
Python>;2.6也支持此功能。
请看这里的文档:Python 3和Python 2
或者使用format()函数,这样更优雅。
format()
percent = 12 print "Percentage: {}%".format(percent)
4年后编辑
现在在Python3x中,{}需要括号。
percent = 12 print ("Percentage: {}%".format(percent))
要打印
%
符号,需要用另一个%
符号“转义”:新的Python 3方法是使用格式字符串。
Python>;2.6也支持此功能。
请看这里的文档:Python 3和Python 2
或者使用
format()
函数,这样更优雅。4年后编辑
现在在Python3x中,{}需要括号。
相关问题 更多 >
编程相关推荐