问题
I need some help with the Python's new string formatter. Basically, I want the outer curly braces to not escape the string replacement field.
This works:
foo = 'bar'
print '{%s}' % foo
But, this doesn't:
foo = 'bar'
print('{{0}}'.format(foo))
Desired output:
'{bar}'
回答1:
It looks like you want:
>>> foo = 'bar'
>>> print('{{{0}}}'.format(foo))
'{bar}'
The outer pair of doubled {{ and }} are copied literally to the output, leaving {0} to be interpreted as a substitution.
回答2:
{{ is an escaped {, but you still need {0} as the placeholder, thus:
print('{{{0}}}'.format('bar'))
来源:https://stackoverflow.com/questions/5533700/python-string-formatting