使用新格式语法打印{和}

jlc*_*lin 20 python

我需要在一个字符串中添加'{'和/或'}',我使用format函数来格式化字符串.例如:我希望我的字符串为"{3}",但是这样:

"\{{}\}".format(3)
Run Code Online (Sandbox Code Playgroud)

给我错误:

ValueError: Single '}' encountered in format string
Run Code Online (Sandbox Code Playgroud)

有谁知道如何在字符串格式中使用'{'和'}'?

谢谢,杰里米

Sve*_*ach 31

只需复制大括号:

>>> "{{{0}}}".format(3)
'{3}'
Run Code Online (Sandbox Code Playgroud)


mou*_*uad 6

print "{{{0}}}".format(3)
'{3}'
Run Code Online (Sandbox Code Playgroud)


Dav*_*e X 6

如果您需要不匹配的括号,您可以使用以下内容:

>>> " {c}{x}{o}{o}".format(o='{',c='}', x=3)
' }3{{' 
Run Code Online (Sandbox Code Playgroud)

加倍也适用于不匹配的大括号:

>>> "}} {} {{ {{".format(3)
'} 3  { {'
Run Code Online (Sandbox Code Playgroud)