python string formatting

穿精又带淫゛_ 提交于 2019-12-23 15:44:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!