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

2024-04-26 21:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码

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

Tags: and代码intestusehavenot情况
3条回答

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

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

这是特别方便,因为你的字符串变得更复杂。

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

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

相关问题 更多 >