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

给我 :Key Error: Hello\\

我想打印输出:{Hello} 42

4

25 回答 25

2822

您需要将{{and加倍}}

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

这是格式字符串语法的 Python 文档的相关部分:

格式字符串包含用大括号括起来的“替换字段” {}。大括号中未包含的任何内容都被视为文字文本,它会原封不动地复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{}}.

于 2011-03-29T00:08:55.973 回答
154

Python 3.6+ (2017)

在最新版本的 Python 中,人们会使用f-strings(另见PEP498)。

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

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

产生所需的

 {Hello} 42

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

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

生产

{hello}
于 2017-12-21T11:12:13.790 回答
99

你通过加倍大括号来逃避它。

例如:

x = "{{ Hello }} {0}"
print(x.format(42))
于 2011-03-29T00:08:22.667 回答
61

OP 写了这条评论:

我试图为某些目的格式化一个小的 JSON,比如:'{"all": false, "selected": "{}"}'.format(data)得到类似的东西{"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 字符串比示例更复杂时,使用该库绝对是更可取的。

于 2016-06-06T18:59:09.003 回答
32

尝试这个:

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

于 2011-03-29T00:08:20.420 回答
29

尝试这样做:

x = " {{ Hello }} {0} "
print x.format(42)
于 2011-03-29T00:08:31.270 回答
17

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

你只需要把它们加倍。

格式{withf'{{'}withf'}}'

所以 :

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

输出 :

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

于 2021-09-24T20:37:44.870 回答
16

虽然不是更好,但仅供参考,您也可以这样做:

>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42

例如,当有人想要打印时,它可能很有用{argument}。它可能比'{{{}}}'.format('argument')

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

于 2015-11-05T11:22:02.420 回答
9

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

>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
于 2019-06-24T19:55:06.450 回答
7

f 字符串(python 3)

可以避免将大括号加倍,方法是仅对您希望应用 f-magic 的字符串部分使用 f-strings 并对所有文字和可能包含“不安全”特殊内容的内容使用常规(哑)字符串人物。让python简单地通过将多个字符串堆叠在一起来为您进行字符串连接。

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

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

注意:字符串之间的换行不是必需的。我添加它们只是为了便于阅读。您也可以编写上面的代码,如下所示:

⚠️ 警告:这可能会伤害您的眼睛或让您头晕目眩!

print("{Hello}"f"{number}""{thanks for all the fish}")
于 2021-07-06T21:55:43.420 回答
6

如果您要经常这样做,那么定义一个实用函数可能会很好,它可以让您使用任意大括号替换,例如

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 的字符串的括号或两个字符串的可迭代(对于多字符分隔符)。

于 2016-11-29T23:43:21.207 回答
5

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

如果性能不是问题,则可以完成工作。

于 2019-12-17T09:37:07.457 回答
5
key = "FOOBAR"
print(f"hello {{{key}}}")

输出

hello {FOOBAR}

如果有人想使用 fstrings 在大括号内打印一些东西。

于 2021-12-23T17:49:33.240 回答
4

我参加这个聚会迟到可笑。我成功地将括号放在替换元素中,如下所示:

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

哪个打印

{hello} {world}

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

于 2020-12-11T19:05:43.623 回答
2

我使用双 {{ }} 来防止 fstring 值注入,

例如,继承我的 Postgres UPDATE 语句来更新一个整数数组列,该列采用 {} 的表达式来捕获数组,即:

端口 = '{100,200,300}'

用 fstrings 它,

ports = [1,2,3]

query = f"""
   UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""

实际的查询语句将是,

UPDATE table SET ports = '{1,2,3}'

这是一个有效的 postgres 语句

于 2021-06-15T02:14:00.410 回答
2

如果您只想打印花括号的一侧:

a=3
print(f'{"{"}{a}')
>>> {3
于 2021-07-25T15:35:22.067 回答
1

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

您可以使用双花括号 {{}} 覆盖它,

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

或者

尝试%s文本格式,

x = " { Hello } %s"
print x%(42)  
于 2017-06-27T12:40:46.310 回答
1

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

从:

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

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

一个更清楚的例子是

string = 10
print(f"{string} {word}")

输出:

NameError: name 'word' is not defined

现在,像这样添加报价墙:

string = 10
print(f"{string}"" {word}")

输出:

10 {word}
于 2020-12-31T21:13:07.180 回答
0

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

假设您想打印出带有索引的多个变量的乘积,例如 在此处输入图像描述,在 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))
于 2019-11-19T18:56:35.610 回答
-1

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

css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'
于 2021-01-28T09:40:38.737 回答
-1

如果您只想打印一个大括号(例如),您可以使用,如果需要,您可以稍后在字符串中添加更多大括号。例如:{{{

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'
于 2020-03-23T01:32:22.513 回答
-1

或者只是参数化支架本身?可能非常冗长。

x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}') 
print(x)
# {42}
于 2021-04-21T17:10:30.807 回答
-2

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

因此,您不会被强制复制花括号,因为所有其他答案都暗示了这一点

于 2020-04-02T11:00:05.710 回答
-3

您可以通过使用原始字符串方法来做到这一点,只需在字符串前添加不带引号的字符 'r'。

# to print '{I am inside braces}'
print(r'{I am inside braces}')
于 2019-09-10T12:30:47.393 回答
-4

使用转义序列来转义 f 字符串中的花括号。例如:打印(f'{a={1}}')

于 2020-06-22T21:54:20.227 回答