非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

当您尝试插入代码字符串时,我建议使用jinja2,它是Python的一个功能齐全的模板引擎,即:

from jinja2 import Template

foo = Template('''
#include <stdio.h>

void main() {
    printf("hello universe number {{number}}");
}
''')

for i in range(2):
    print(foo.render(number=i))

所以你不会像其他答案所暗示的那样被迫复制大括号

其他回答

我在尝试打印文本时遇到了这个问题,我可以将文本复制粘贴到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))

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

你只需要把它们加倍。

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

So :

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

输出:

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

对于确切的示例,OR:

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

将打印:

{你好}42

如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'

OP撰写了以下评论:

我试图为某些目的格式化一个小JSON,例如:“{”all“:false,”selected“:”{}“}”。格式化(数据)以获得类似于{”all:false,“selected”:“1,2”}的内容

在处理JSON时,“转义括号”问题很常见。

我建议这样做:

import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)

它比替代方案更干净,即:

'{{"all": false, "selected": "{}"}}'.format(data)

当json字符串比示例更复杂时,使用json库无疑是更好的选择。

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

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