非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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

你只需要把它们加倍。

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

So :

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

输出:

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

对于确切的示例,OR:

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

将打印:

{你好}42

其他回答

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

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

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

or

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

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

试试看:

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

虽然不是更好,但仅供参考,您也可以这样做:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42

例如,当有人想要打印{argument}时,它会很有用。它可能比“{{}}”更可读。format(“argument”)

注意,在Python 2.7之后省略了参数位置(例如{}而不是{0})

我使用了双{{}}来防止fstring值注入,

例如,这里是我的Postgres UPDATE语句,用于更新整数数组列,该列采用表达式{}来捕获数组,即:

ports=“{100200300}”

使用fstrings,

ports = [1,2,3]

query = f"""
   UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""

实际查询语句将是,

UPDATE table SET ports = '{1,2,3}'

这是一个有效的延期

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

>>> 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'