非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'
其他回答
我使用了双{{}}来防止fstring值注入,
例如,这里是我的Postgres UPDATE语句,用于更新整数数组列,该列采用表达式{}来捕获数组,即:
ports=“{100200300}”
使用fstrings,
ports = [1,2,3]
query = f"""
UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""
实际查询语句将是,
UPDATE table SET ports = '{1,2,3}'
这是一个有效的延期
key = "FOOBAR"
print(f"hello {{{key}}}")
输出
hello {FOOBAR}
万一有人想用fstrings在大括号内打印东西。
我在尝试打印文本时遇到了这个问题,我可以将文本复制粘贴到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-string模板中需要大括号,则需要在f-string的一组大括号中输出包含两个大括号的字符串:
css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'
或者只是参数化括号本身?可能很冗长。
x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}')
print(x)
# {42}