我有下面的代码
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
您不能有选择地转义%,因为%总是有一个特殊的含义,这取决于后面的字符。
在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)
用你已经掌握的知识。