非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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

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

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

or

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

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

其他回答

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

发件人:

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

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

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

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

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

试试看:

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

我最近遇到了这个问题,因为我想将字符串注入到预先格式化的JSON中。我的解决方案是创建一个助手方法,如下所示:

def preformat(msg):
    """ allow {{key}} to be used for formatting in text
    that already uses curly braces.  First switch this into
    something else, replace curlies with double curlies, and then
    switch back to regular braces
    """
    msg = msg.replace('{{', '<<<').replace('}}', '>>>')
    msg = msg.replace('{', '{{').replace('}', '}}')
    msg = msg.replace('<<<', '{').replace('>>>', '}')
    return msg

然后,您可以执行以下操作:

formatted = preformat("""
    {
        "foo": "{{bar}}"
    }""").format(bar="gas")

如果性能不是问题,则获取完成的作业。