python - 如何使用字符串格式打印 '%' 标志?

标签 python printing python-2.x percentage

<分区>

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

一开始就试过了 - 没用...

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%

关于python - 如何使用字符串格式打印 '%' 标志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28343745/

相关文章:

python 类在 __init__ 中使用 super 调用自身

python - 用于半实现抽象类的 Pylint

android - 从服务器 URL 打印 pdf

python - 跨多个键对嵌套字典进行排序

python - PDFMiner - 遍历页面并将它们转换为文本

python - 将字符串转换为 int 太慢

C# 控制台 - 将光标位置设置为最后一个可见行

macos - 如何在 OS X 上将低级转义序列发送到打印机?

python - __new__ 是检索 SQLAlchemy 对象的好方法吗

python - 如何在队列中放置和获取一组多个项目?