我有下面的代码

test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test

print(selectiveEscape)

我想要得到输出:

Print percent % in sentence and not have it break.

实际发生了什么:

    selectiveEscape = "Use percent % in sentence and not %s" % test
TypeError: %d format: a number is required, not str

当前回答

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.

其他回答

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.

或者,从Python 2.6开始,你可以使用新的字符串格式(在PEP 3101中描述):

'Print percent % in sentence and not {0}'.format(test)

当你的字符串变得更复杂时,这尤其方便。

您不能有选择地转义%,因为%总是有一个特殊的含义,这取决于后面的字符。

在Python文档中,在该部分的第二个表的底部,它声明:

'%'        No argument is converted, results in a '%' character in the result.

因此,你应该使用:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(请注意将tuple的参数明确地更改为%)

如果不知道这些,我可能会这样做:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

用你已经掌握的知识。

如果你正在使用Python 3.6或更新版本,你可以使用f-string:

>>> test = "have it break."
>>> selectiveEscape = f"Print percent % in sentence and not {test}"
>>> print(selectiveEscape)
... Print percent % in sentence and not have it break.

尝试使用%%打印%符号。