非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
如果只想打印一个大括号(例如{),可以使用{{,如果需要,可以稍后在字符串中添加更多大括号。例如:
>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'
其他回答
您需要将{{和}}加倍:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
以下是Python文档中有关格式字符串语法的相关部分:
格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文字文本,并将其原样复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{和}}对其进行转义。
如果只想打印一个大括号(例如{),可以使用{{,如果需要,可以稍后在字符串中添加更多大括号。例如:
>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'
尝试这样做:
x = " {{ Hello }} {0} "
print x.format(42)
我最近遇到了这个问题,因为我想将字符串注入到预先格式化的JSON中。我的解决方案是创建一个助手方法,如下所示:
def preformat(msg):
""" allow {{key}} to be used for formatting in text
that already uses curly braces. First switch this into
something else, replace curlies with double curlies, and then
switch back to regular braces
"""
msg = msg.replace('{{', '<<<').replace('}}', '>>>')
msg = msg.replace('{', '{{').replace('}', '}}')
msg = msg.replace('<<<', '{').replace('>>>', '}')
return msg
然后,您可以执行以下操作:
formatted = preformat("""
{
"foo": "{{bar}}"
}""").format(bar="gas")
如果性能不是问题,则获取完成的作业。
OP撰写了以下评论:
我试图为某些目的格式化一个小JSON,例如:“{”all“:false,”selected“:”{}“}”。格式化(数据)以获得类似于{”all:false,“selected”:“1,2”}的内容
在处理JSON时,“转义括号”问题很常见。
我建议这样做:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
它比替代方案更干净,即:
'{{"all": false, "selected": "{}"}}'.format(data)
当json字符串比示例更复杂时,使用json库无疑是更好的选择。