【问题标题】:How can I selectively escape percent (%) in Python strings?如何选择性地转义 Python 字符串中的百分比 (%)?
【发布时间】:2019-10-04 11:56:25
【问题描述】:

我有以下代码

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


【解决方案1】:

如果您使用的是 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.

【讨论】:

  • 很高兴看到如何逃脱{这里
  • 你只要把它加倍{{
【解决方案2】:

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

在 Python 的 documentation 中,在该部分第二个表的底部,它指出:

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

因此你应该使用:

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

(请注意将显式更改为元组作为% 的参数)

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

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

显然你已经掌握了知识。

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

      尝试使用%% 打印 % sign 。

      【讨论】:

        【解决方案5】:

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

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

        当您的字符串变得越来越复杂时,这特别方便。

        【讨论】:

        • +1,虽然我认为 op 正在寻找基于 % 的答案,但这些天我更喜欢使用 format
        • 唯一的问题是当您要格式化的文本是带有 CSS 样式部分的 HTML 时。
        • 对于包含 CSS 样式部分 @Broseph 的文本格式 HTML,您有什么建议?
        • 我错了。如果你在你的 CSS 中使用双括号,那就没问题了。
        【解决方案6】:
        >>> 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 3.3.5 中,print('%s%%' % 100) 打印 100%。但是print('%%') 打印出%%。因此,如果您不进行替换,看起来您不必转义 % 符号。
        • @Zenadix 在 Python 2.7 中也是如此
        • 请注意,% 方法实际上已被弃用(在 Python 3 中),取而代之的是 str.format()docs.python.org/2/library/stdtypes.html#str.format
        • 请注意,% 方法在 Python 3.6 中并未贬值。它将继续得到支持,以代替它与 c、c++ 等的相似性。str.format() 和 f 字符串是首选但不强制执行。
        • 刚刚注意到,如果字符串是 json 字符串,则从文件中读取您甚至不需要转义 % 符号。只需% 即可
        猜你喜欢
        • 2012-05-27
        • 2020-11-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        • 2017-04-30
        相关资源
        最近更新 更多