python字符串格式

csa*_*ons 3 python string format

我需要一些Python的新字符串格式化程序的帮助.基本上,我希望外部花括号不会逃脱字符串替换字段.

这有效:

foo = 'bar'
print '{%s}' % foo
Run Code Online (Sandbox Code Playgroud)

但是,这不是:

foo = 'bar'
print('{{0}}'.format(foo))
Run Code Online (Sandbox Code Playgroud)

期望的输出:

'{酒吧}'

Gre*_*ill 7

它看起来像你想要的:

>>> foo = 'bar'
>>> print('{{{0}}}'.format(foo))
'{bar}'
Run Code Online (Sandbox Code Playgroud)

外部对的doubled {{}}字面复制到输出,留下{0}来被解释为替换.