我如何有select地逃避Pythonstring中的百分比(%)?

我有以下代码

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. 

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

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

当你的string变得更加复杂的时候,这特别方便。

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

如果从文件中读取格式化模板,并且无法确保内容使百分号加倍,那么您可能必须检测百分号字符,并以编程方式决定是否是占位符的开始。 然后,parsing器还应该识别%d (以及其他可以使用的字母)等序列,还可以识别%(xxx)s等。

类似的问题可以观察到新的格式 – 文本可以包含花括号。

你不能有select地逃避% ,因为根据下面的字符, %总是有特殊的含义。

在Python的文档中,在该部分的第二个表格的部分,它指出:

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

所以你应该使用:

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

(请注意对元组的expicit更改作为%参数)

不知道上述,我会做:

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

知道你显然已经有了。