如何使用字符串格式打印'%'符号?

Eri*_*989 19 python printing python-2.x percentage

我用计算器百分比制作了一个小脚本; 但是,我希望在打印的消息中包含'%'...

在开始时试过这个 - 没有用......

oFile.write("百分比:%s%"\n"%%)

然后我尝试了"Percentage: %s"%"\n" % percent"哪些不起作用.

我希望输出为:百分比:x%

我一直得到"TypeError:在字符串格式化过程中没有转换所有参数"

bvi*_*dal 41

要打印%标志,您需要用另一个%标志"逃避"它:

percent = 12
print "Percentage: %s %%\n" % percent  # Note the double % sign
>>> Percentage: 12 %
Run Code Online (Sandbox Code Playgroud)


GLH*_*LHF 11

或者使用format()功能,更优雅.

percent = 12
print "Percentage: {}%".format(percent)
Run Code Online (Sandbox Code Playgroud)

4年后编辑

现在在Python3x中print()需要括号.

percent = 12
print ("Percentage: {}%".format(percent))
Run Code Online (Sandbox Code Playgroud)


小智 5

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()
Run Code Online (Sandbox Code Playgroud)

示例输出:

Original Number:  0.25                                                                                        
Formatted Number with percentage: 25.00%                                                                      
Original Number:  -0.25                                                                                       
Formatted Number with percentage: -25.00% 
Run Code Online (Sandbox Code Playgroud)

帮助正确设置百分比值的格式

+++

使用百分比的 ascii 值 - 即 37

print( '12' + str(chr(37)) )
Run Code Online (Sandbox Code Playgroud)