如何在Python字符串中有选择地转义百分比(%)?

如何在Python字符串中有选择地转义百分比(%)?,python,escaping,python-2.7,Python,Escaping,Python 2.7,我有以下代码 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 = "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 2.6开始,您可以使用新的字符串格式(如中所述):


当字符串变得越来越复杂时,这尤其方便。

尝试使用
%%
打印%符号

如果格式模板是从文件中读取的,并且您无法确保内容将百分号加倍,那么您可能必须检测百分号,并通过编程确定它是否是占位符的开头。然后,解析器还应该识别像
%d
(以及可以使用的其他字母)这样的序列,但也应该识别
%(xxx)s


新格式也存在类似的问题——文本可以包含大括号。

您不能有选择地转义
%
,因为
%
根据以下字符总是有特殊含义

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

'%'        No argument is converted, results in a '%' character in the result.
因此,您应该使用:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(请注意将expicit更改为tuple作为
%
的参数)

如果不知道上述情况,我会:

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

如果您使用的是Python 3.6或更新版本,您可以使用:


+1,虽然我认为op正在寻找基于%的答案,但我现在更喜欢使用
格式
。唯一的问题是,当您要格式化的文本是带有CSS样式部分的HTML时。对于包含CSS样式部分的文本格式化HTML,@Broseph,您有什么建议?我错了。如果你在CSS中使用双大括号,你就可以了。为什么它不是
\%
?这是我的猜测,我惊讶地发现它是
%%
而不是-看起来很违反直觉整数的十进制表示,用空格填充。转义是函数,而不是语言语法。因此,如果转义是
\%
,那么当用普通代码编写时,它实际上是
\\%
是我见过的典型模式,不管好坏,
\
恰好是最常见的转义字符。@Demis如果必须打印
\\%
,如何转义
\
?如果特殊字符也不特殊(取决于具体情况),那么您肯定需要通过重复特殊字符进行转义。我认为在Python中,文本%由“%%”而不是“\%”编码是令人讨厌的。在Python 3.3.5中,
print(“%s%%”%100)
打印
100%
。但是
打印('%%')
打印
%%
。因此,如果不进行替换,您似乎不必逃过%符号。@Zenadix在Python 2.7中也是如此。请注意,
%
方法实际上已被弃用(在Python 3中),取而代之的是
str.format()
:请注意,
%
方法在Python 3.6中没有被弃用。将继续支持它与C、C++等类似的代码< >代码> Str.Falm()/Fix>,F字符串是首选的,但不是强制执行的。注意,如果字符串是JSON字符串,从文件中读取,甚至不需要逃避<代码> %<代码>符号。只要
%
就能很好地看到如何逃逸{这里你只要把它加倍
{
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
>>> test = "have it break."
>>> selectiveEscape = f"Print percent % in sentence and not {test}"
>>> print(selectiveEscape)
... Print percent % in sentence and not have it break.