非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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

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

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

注意,在Python 2.7之后省略了参数位置(例如{}而不是{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}

试试看:

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

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

>>> 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 = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}

尝试这样做:

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