非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

Python 3.6+(2017)

在最近的Python版本中,可以使用f-string(另请参见PEP498)。

对于f字符串,应该使用双{{或}}

n = 42  
print(f" {{Hello}} {n} ")

产生所需的

 {Hello} 42

如果需要解析括号中的表达式而不是使用文本,则需要三组括号:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

生产

{hello}

其他回答

如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'

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

x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}
key = "FOOBAR"
print(f"hello {{{key}}}")

输出

hello {FOOBAR}

万一有人想用fstrings在大括号内打印东西。

我最近遇到了这个问题,因为我想将字符串注入到预先格式化的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=“{{你好}}{0}”