非工作示例:

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

其他回答

或者只是参数化括号本身?可能很冗长。

x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}

你可以通过加倍牙套来逃避。

Eg:

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

我使用了双{{}}来防止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}'

这是一个有效的延期

我在尝试打印文本时遇到了这个问题,我可以将文本复制粘贴到Latex文档中。我扩展了这个答案,并使用了命名替换字段:

假设您要打印多个变量的乘积,其中包含以下索引,在乳胶中为$A_{0042}*A_{3141}*A_{2718}*A_{0042}$以下代码使用命名字段执行此项工作,以便对许多索引保持可读:

idx_mapping = {'i1':42, 'i2':3141, 'i3':2178 }
print('$A_{{ {i1:04d} }} * A_{{ {i2:04d} }} * A_{{ {i3:04d} }} * A_{{ {i1:04d} }}$'.format(**idx_mapping))

我最近遇到了这个问题,因为我想将字符串注入到预先格式化的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")

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