非工作示例:

print(" \{ Hello \} {0} ".format(42))

所需输出:

 {Hello} 42 

当前回答

或者只是参数化括号本身?可能很冗长。

x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}

其他回答

您需要将{{和}}加倍:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

以下是Python文档中有关格式字符串语法的相关部分:

格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文字文本,并将其原样复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{和}}对其进行转义。

原因是,{}是.format()的语法,因此在您的情况下.format)无法识别{Hello},因此引发了错误。

可以通过使用双花括号{{}}来覆盖它,

x = " {{ Hello }} {0} "

or

尝试%s进行文本格式化,

x = " { Hello } %s"
print x%(42)  

您想用字符{或}格式化字符串

你只需要把它们加倍。

格式{带有f“{{”,}带有f‘}}”

So :

name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')

输出:

你好,鲍勃!我想打印}和{或{}

对于确切的示例,OR:

number = 42
print(f'{{Hello}} {number}')

将打印:

{你好}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")

如果性能不是问题,则获取完成的作业。

尝试这样做:

x = " {{ Hello }} {0} "
print x.format(42)