使用单个变量格式化多个 %s

Rod*_*lfo 2 python string-formatting

我有一个未知数量的字符串%s,需要使用单个字符串进行格式化。

例如,如果我有一个字符串并想用它应该输出的"%s some %s words %s"单词对其进行格式化house"house some house words house"

执行以下操作会给我一个错误:

>>> "%s some %s words %s" % ("house")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
Run Code Online (Sandbox Code Playgroud)

因此,我决定执行以下操作,这可行,但对于这样一个简单的问题来说似乎过于复杂。

var = "house"
tup = (var,)
while True:
    try:
        print "%s some %s words %s" % tup
        break
    except:
        tup += (var,)
Run Code Online (Sandbox Code Playgroud)

有没有更Pythonic的方法来做到这一点?

kin*_*all 5

如果你确定你正在替补,%s你可以这样做:

var = "house"
tup = (var,)
txt = "%s some %s words %s"

print txt % (tup * txt.count("%s"))
Run Code Online (Sandbox Code Playgroud)

但更好的解决方案是使用str.format()which 使用不同的语法,但允许您按数字指定项目,以便您可以重用它们:

var = "house"
txt = "{0} some {0} words {0}"

print txt.format(var)
Run Code Online (Sandbox Code Playgroud)

  • 对于 `%s` 版本,您可能需要执行类似 `txt % (tup * re.findall(r'%%|%s', txt).count('%s'))` 的操作来避免对实例进行计数的“%s”,其中“%”被转义。 (2认同)