Python 如何使用字符串格式打印“%”符号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28343745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I print a '%' sign using string formatting?
提问by Eric1989
I've made a little script to calculator percent; however, I wish to actually include the '%' within the message printed...
我制作了一个小脚本来计算百分比;但是,我希望在打印的消息中实际包含 '%'...
Tried this at the start - didn't work...
一开始就试过这个 - 没有用...
oFile.write("Percentage: %s%"\n" % percent)
oFile.write("百分比:%s%"\n" %%)
I then tried "Percentage: %s"%"\n" % percent"
which didn't work.
然后我尝试了"Percentage: %s"%"\n" % percent"
哪个不起作用。
I'd like the output to be: Percentage: x%
我希望输出为:百分比:x%
I keep getting "TypeError: not all arguments converted during string formatting"
我不断收到“类型错误:并非所有参数都在字符串格式化期间转换”
采纳答案by bvidal
To print the %
sign you need to 'escape' it with another %
sign:
要打印%
标志,您需要用另一个%
标志“转义”它:
percent = 12
print "Percentage: %s %%\n" % percent # Note the double % sign
>>> Percentage: 12 %
回答by GLHF
Or use format()
function, which is more elegant.
或者使用format()
函数,更优雅。
percent = 12
print "Percentage: {}%".format(percent)
4 years later edit
4年后编辑
Now In Python3x print()
requires parenthesis.
现在在 Python3x 中print()
需要括号。
percent = 12
print ("Percentage: {}%".format(percent))
回答by js837
回答by Thomas Vetterli
format()
is more elegant but the modulo sign seems to be quicker!
format()
更优雅,但模符号似乎更快!
http://inre.dundeemt.com/2016-01-13/string-modulo-vs-format-fight/- shows that modulo is ~30% faster!
http://inre.dundeemt.com/2016-01-13/string-modulo-vs-format-fight/- 显示模数快了约 30%!
回答by Ram Prajapati
x = 0.25
y = -0.25
print("\nOriginal Number: ", x)
print("Formatted Number with percentage: "+"{:.2%}".format(x));
print("Original Number: ", y)
print("Formatted Number with percentage: "+"{:.2%}".format(y));
print()
Sample Output:
示例输出:
Original Number: 0.25
Formatted Number with percentage: 25.00%
Original Number: -0.25
Formatted Number with percentage: -25.00%
Helps in proper formatting of percentage value
有助于正确格式化百分比值
+++
+++
Using ascii value of percentage - which is 37
使用百分比的 ascii 值 - 即 37
print( '12' + str(chr(37)) )