x = " \{ Hello \} {0} "
print(x.format(42))
给我 :Key Error: Hello\\
我想打印输出:{Hello} 42
x = " \{ Hello \} {0} "
print(x.format(42))
给我 :Key Error: Hello\\
我想打印输出:{Hello} 42
您需要将{{
and加倍}}
:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
这是格式字符串语法的 Python 文档的相关部分:
格式字符串包含用大括号括起来的“替换字段”
{}
。大括号中未包含的任何内容都被视为文字文本,它会原封不动地复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{
和}}
.
你通过加倍大括号来逃避它。
例如:
x = "{{ Hello }} {0}"
print(x.format(42))
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 字符串比示例更复杂时,使用该库绝对是更可取的。
尝试这个:
x = "{{ Hello }} {0}"
尝试这样做:
x = " {{ Hello }} {0} "
print x.format(42)
您想用字符格式化字符串{
或}
你只需要把它们加倍。
格式{
withf'{{'
和}
withf'}}'
所以 :
name = "bob"
print(f'Hello {name} ! I want to print }} and {{')
输出 :
你好鲍勃!我想打印 } 和 {
虽然不是更好,但仅供参考,您也可以这样做:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
例如,当有人想要打印时,它可能很有用{argument}
。它可能比'{{{}}}'.format('argument')
请注意,您在 Python 2.7 之后省略了参数位置(例如{}
,而不是){0}
如果需要在字符串中保留两个花括号,则需要在变量的每一侧使用 5 个花括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
您可以避免将大括号加倍,方法是仅对您希望应用 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}")
如果您要经常这样做,那么定义一个实用函数可能会很好,它可以让您使用任意大括号替换,例如
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 的字符串的括号或两个字符串的可迭代(对于多字符分隔符)。
我最近遇到了这个问题,因为我想将字符串注入到预先格式化的 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")
如果性能不是问题,则可以完成工作。
key = "FOOBAR"
print(f"hello {{{key}}}")
输出
hello {FOOBAR}
如果有人想使用 fstrings 在大括号内打印一些东西。
我参加这个聚会迟到可笑。我成功地将括号放在替换元素中,如下所示:
print('{0} {1}'.format('{hello}', '{world}'))
哪个打印
{hello} {world}
严格来说,这不是 OP 所要求的,因为他/她想要格式字符串中的大括号,但这可能会对某人有所帮助。
我使用双 {{ }} 来防止 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 语句
如果您只想打印花括号的一侧:
a=3
print(f'{"{"}{a}')
>>> {3
原因是,在您的情况下,so{}
的语法无法识别,因此引发了错误。.format()
.format()
{Hello}
您可以使用双花括号 {{}} 覆盖它,
x = " {{ Hello }} {0} "
或者
尝试%s
文本格式,
x = " { Hello } %s"
print x%(42)
您可以使用“引用墙”将格式化字符串部分与常规字符串部分分开。
从:
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}
我在尝试打印文本时偶然发现了这个问题,我可以将其复制粘贴到 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))
如果您需要可以格式化的 f 字符串模板中的花括号,您需要在 f 字符串的一组花括号中输出一个包含两个花括号的字符串:
css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'
如果您只想打印一个大括号(例如),您可以使用,如果需要,您可以稍后在字符串中添加更多大括号。例如:{
{{
>>> 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'
或者只是参数化支架本身?可能非常冗长。
x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}')
print(x)
# {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))
因此,您不会被强制复制花括号,因为所有其他答案都暗示了这一点
您可以通过使用原始字符串方法来做到这一点,只需在字符串前添加不带引号的字符 'r'。
# to print '{I am inside braces}'
print(r'{I am inside braces}')
使用转义序列来转义 f 字符串中的花括号。例如:打印(f'{a={1}}')