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)
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)
| 归档时间: |
|
| 查看次数: |
2155 次 |
| 最近记录: |