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

jon*_*man 332 python escaping python-2.7

我有以下代码

test = "have it break."
selectiveEscape = "Print percent % in sentence and not %s" % test

print(selectiveEscape)
Run Code Online (Sandbox Code Playgroud)

我想获得输出:

Print percent % in sentence and not have it break.
Run Code Online (Sandbox Code Playgroud)

实际发生了什么:

    selectiveEscape = "Use percent % in sentence and not %s" % test
TypeError: %d format: a number is required, not str
Run Code Online (Sandbox Code Playgroud)

Nol*_*lty 580

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
Run Code Online (Sandbox Code Playgroud)

  • 在Python 3.3.5中,`print('%s %%'%100)`打印`100%`.但是`print('%%')`打印`%%`.因此,如果您不进行替换,看起来您不必逃避%符号. (34认同)
  • 请注意,Python 3.6中不会折旧`%`方法.它将继续得到支持,以代替它与c,c ++等的相似性.`str.format()`和f-strings是首选但不强制执行. (6认同)
  • @Zenadix在Python 2.7中也是如此 (5认同)
  • 注意`%`方法实际上已被弃用(在Python 3中),而不是`str.format()`:https://docs.python.org/2/library/stdtypes.html#str.format (2认同)

Kar*_*mel 55

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

'Print percent % in sentence and not {0}'.format(test)
Run Code Online (Sandbox Code Playgroud)

当你的琴弦变得更复杂时,这尤其方便.

  • 唯一的问题是当您要格式化的文本是带有CSS样式部分的HTML时. (2认同)

小智 36

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


Jar*_*děk 6

如果您使用的是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.
Run Code Online (Sandbox Code Playgroud)


Ant*_*hon 5

您不能有选择地逃避%,因为%总是具有特殊含义,具体取决于以下字符.

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

'%'        No argument is converted, results in a '%' character in the result.
Run Code Online (Sandbox Code Playgroud)

因此你应该使用:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
Run Code Online (Sandbox Code Playgroud)

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

如果不知道上述内容,我会做到:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
Run Code Online (Sandbox Code Playgroud)

凭借你显然已经拥有的知识.