【发布时间】:2012-05-27 12:56:16
【问题描述】:
我有以下代码
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
【问题讨论】:
-
为什么不是
\%?这是我的猜测,我惊讶地发现它是%%- 似乎很违反直觉。 -
% i表示“整数的十进制表示,用空格填充。 -
转义是函数,而不是语言语法。因此,如果转义是
\%,那么在用普通代码编写时,它实际上是\\%。<escape><escape>是我见过的典型模式,\恰好是最常见的转义字符,无论好坏。 -
@Demis 如果你必须打印
\\%,你如何逃避\?如果特殊字符根据情况也不是特殊的,您肯定需要通过重复特殊字符来进行转义。 -
我认为在 Python 中文字 % 是由 "%%" 而不是 "\%" 编码的,这很烦人。
标签: python escaping python-2.7