字符串包含“%s"时的 Python 字符串格式化不逃避 [英] Python string formatting when string contains "%s" without escaping
问题描述
格式化字符串时,我的字符串可能包含我不希望转换的模 "%"
.我可以转义字符串并将每个 "%"
更改为 "%%"
作为解决方法.
When formatting a string, my string may contain a modulo "%"
that I do not wish to have converted. I can escape the string and change each "%"
to "%%"
as a workaround.
例如,
'Day old bread, 50%% sale %s' % 'today!'
输出:
'Day old bread, 50% sale today'
但是除了逃避还有其他选择吗?我希望使用 dict 可以让 Python 忽略任何非关键字转换.
例如,
But are there any alternatives to escaping? I was hoping that using a dict would make it so Python would ignore any non-keyword conversions.
e.g.,
'Day old bread, 50% sale %(when)s' % {'when': 'today'}
但 Python 仍然看到第一个模 %
并给出:
but Python still sees the first modulo %
and gives a:
TypeError: not enough arguments for format string
推荐答案
您可以(并且应该)使用 新字符串 .format()
方法(如果您有 Python 2.6 或更高版本):
You could (and should) use the new string .format()
method (if you have Python 2.6 or higher) instead:
"Day old bread, 50% sale {0}".format("today")
文档还说旧的 %
格式最终将从语言中删除,尽管这肯定需要一些时间.新的格式化方法更强大,所以这是一件好事.
The docs also say that the old %
formatting will eventually be removed from the language, although that will surely take some time. The new formatting methods are way more powerful, so that's a Good Thing.
这篇关于字符串包含“%s"时的 Python 字符串格式化不逃避的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!