如何有选择地转义 Python 字符串中的百分比 (%)?
- 2024-12-18 08:39:00
- admin 原创
- 122
问题描述:
我有以下代码
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
解决方案 1:
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
解决方案 2:
或者,从 Python 2.6 开始,您可以使用新的字符串格式(如PEP 3101中所述):
'Print percent % in sentence and not {0}'.format(test)
当你的字符串变得越来越复杂时这尤其方便。
解决方案 3:
尝试使用它%%
来打印% 符号。
解决方案 4:
您不能有选择地转义%
,因为%
根据后面的字符,它总是具有特殊含义。
在 Python 的文档中,该部分第二个表的底部指出:
'%' 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)
你显然已经掌握了这些知识。
解决方案 5:
如果您使用的是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.
解决方案 6:
如果格式化模板是从文件中读取的,并且您无法确保内容将百分号加倍,那么您可能必须检测百分号字符并以编程方式确定它是否是占位符的开头。然后解析器还应该识别诸如%d
(以及可以使用的其他字母)之类的序列,还有%(xxx)s
等等。
在新格式中也可以观察到类似的问题——文本可以包含花括号。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD