非工作示例:

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

所需输出:

 {Hello} 42 

当前回答

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

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的字符串或两个字符串的可迭代(对于多字符分隔符)的情况下工作。

其他回答

我参加这个聚会迟到了,真是可笑。我成功地将支架放置在替换元件中,如下所示:

print('{0} {1}'.format('{hello}', '{world}'))

打印

{hello} {world}

严格地说,这不是OP所要求的,因为他/她希望格式字符串中包含大括号,但这可能会对某人有所帮助。

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

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

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

or

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

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

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

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

f-string(python 3)

通过只对字符串中要应用f-magic的部分使用f-string,并对所有文字和可能包含“不安全”特殊字符的部分使用常规(哑)字符串,可以避免使用双括号。让python简单地通过将多个字符串堆叠在一起来完成字符串连接。

number = 42
print(" { Hello }"  
f" {number} " 
"{ thanks for all the fish }")

### OUTPUT:
{ Hello } 42 { thanks for all the fish }

注意:字符串之间不需要换行符。我只是为了可读性而添加了它们。您还可以编写上面的代码,如下所示:⚠️ 警告:这可能会伤害你的眼睛或使你头晕!打印(“{你好}”f“{号码}”“{感谢所有的鱼}”)

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

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