非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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

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

打印

{hello} {world}

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

其他回答

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

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

打印

{hello} {world}

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

当您尝试插入代码字符串时,我建议使用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(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}
key = "FOOBAR"
print(f"hello {{{key}}}")

输出

hello {FOOBAR}

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

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

你只需要把它们加倍。

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

So :

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

输出:

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

对于确切的示例,OR:

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

将打印:

{你好}42