非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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

输出

hello {FOOBAR}

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

其他回答

如果只想打印一个大括号(例如{),可以使用{{,如果需要,可以稍后在字符串中添加更多大括号。例如:

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'

试试看:

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

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

输出

hello {FOOBAR}

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

如果在可以格式化的f-string模板中需要大括号,则需要在f-string的一组大括号中输出包含两个大括号的字符串:

css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'

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

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

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

or

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

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