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

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

我有以下代码

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

我想获得输出:

Print percent % in sentence and not have it break.

实际发生了什么:

    selectiveEscape = "Use percent % in sentence and not %s" % testTypeError: %d format: a number is required, not str


30秒到达战场
浏览 1088回答 3
3回答

陪伴而非守候

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

白猪掌柜的

或者,从Python 2.6开始,您可以使用新的字符串格式(在PEP 3101中描述):'Print percent % in sentence and not {0}'.format(test)当你的琴弦变得更复杂时,这尤其方便。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python