非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

你可以通过加倍牙套来逃避。

Eg:

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

其他回答

当您尝试插入代码字符串时,我建议使用jinja2,它是Python的一个功能齐全的模板引擎,即:

from jinja2 import Template

foo = Template('''
#include <stdio.h>

void main() {
    printf("hello universe number {{number}}");
}
''')

for i in range(2):
    print(foo.render(number=i))

所以你不会像其他答案所暗示的那样被迫复制大括号

我参加这个聚会迟到了,真是可笑。我成功地将支架放置在替换元件中,如下所示:

print('{0} {1}'.format('{hello}', '{world}'))

打印

{hello} {world}

严格地说,这不是OP所要求的,因为他/她希望格式字符串中包含大括号,但这可能会对某人有所帮助。

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

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

试试看:

x=“{{你好}}{0}”

您可以使用“引号墙”将格式化字符串部分与常规字符串部分分开。

发件人:

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

to

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

一个更清楚的例子是

string = 10
print(f"{string} {word}")

输出:

NameError: name 'word' is not defined

现在,添加报价墙,如下所示:

string = 10
print(f"{string}"" {word}")

输出:

10 {word}