非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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

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

其他回答

key = "FOOBAR"
print(f"hello {{{key}}}")

输出

hello {FOOBAR}

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

尝试这样做:

x = " {{ Hello }} {0} "
print x.format(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}

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

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

打印

{hello} {world}

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

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

发件人:

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}