非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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库无疑是更好的选择。

其他回答

如果你要经常这样做,最好定义一个实用函数,让你使用任意的大括号替代,比如

def custom_format(string, brackets, *args, **kwargs):
    if len(brackets) != 2:
        raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
    padded = string.replace('{', '{{').replace('}', '}}')
    substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
    formatted = substituted.format(*args, **kwargs)
    return formatted

>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'

注意,这将在括号是长度为2的字符串或两个字符串的可迭代(对于多字符分隔符)的情况下工作。

试试看:

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

当您尝试插入代码字符串时,我建议使用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))

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

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

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

Python 3.6+(2017)

在最近的Python版本中,可以使用f-string(另请参见PEP498)。

对于f字符串,应该使用双{{或}}

n = 42  
print(f" {{Hello}} {n} ")

产生所需的

 {Hello} 42

如果需要解析括号中的表达式而不是使用文本,则需要三组括号:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

生产

{hello}