在字符串格式中,我一次只能替换一个参数吗?

sag*_*gar 8 python string-formatting python-3.x

有什么办法我只能在字符串格式中只替换第一个参数吗?像这样:

"My quest is {test}{}".format(test="test")
Run Code Online (Sandbox Code Playgroud)

我希望输出为:

"My quest is test {}
Run Code Online (Sandbox Code Playgroud)

{}我将在稍后更换第二个arg.

我知道我可以创建一个字符串:

"My quest is {test}".format(test="test")
Run Code Online (Sandbox Code Playgroud)

然后将它与剩余的字符串组合并创建新的字符串,但我可以一次性完成吗?

Blc*_*ght 13

如果您知道何时设置格式字符串,您将只替换值的子集,并且您希望保留其他一些集合,则可以通过加倍括号来逃避那些您不会立即填充的字符串:

x = "foo {test} bar {{other}}".format(test="test") # other won't be filled in here
print(x)                              # prints "foo test bar {other}"
print(x.format(other="whatever"))     # prints "foo test bar whatever"
Run Code Online (Sandbox Code Playgroud)

  • 因此,如果我需要格式化,比如说 4 次,我需要将一些占位符包装到 4 对括号中,如下所示: `my_str = "{first}, {{second}}, {{{third}}}, {{{{第四}}}}“`? (3认同)
  • 不,每次都需要加倍:`"{first}, {{second}}, {{{{third}}}}, {{{{{{{fourth}}}}}}}}"` 。您可能想使用其他方法之一(例如“second =”{second}“”,如果这是您确实需要做的事情。 (3认同)

Mor*_*enB 10

使用命名参数并用相同的参数替换其他参数。

经常使用它来“规范化字符串”,以便它们预先适合一般模式:

>>> x = "foo {test} bar {other}"
>>> x = x.format(test='test1', other='{other}') 
>>> x
'foo test1 bar {other}'
>>> x = x.format(other='other1')                
>>> x
'foo test1 bar other1'
Run Code Online (Sandbox Code Playgroud)