在三引号Python字符串中转义{}括号

时间:2019-06-05 13:56:19

标签: python python-3.x string formatting

如何在Python 3中格式化这种形式的字符串?

'''{name}{{name}}'''.format(name="bob")

所需的输出为:bob{bob},但以上给出的为:bob{name}

一种解决方案是向format添加另一个参数:

'''{name1}{name2}'''.format(name1="bob", name2="{bob}")

但这太过分了。有没有一种方法可以正确地转义{,以便仍可以对内部{x}进行插值并且只能将单个name传递给format

1 个答案:

答案 0 :(得分:4)

再添加一层{}

'''{name}{{{name}}}'''.format(name="bob")

输出:

bob{bob}