非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
如果只想打印一个大括号(例如{),可以使用{{,如果需要,可以稍后在字符串中添加更多大括号。例如:
>>> 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'
其他回答
如果要仅打印大括号的一侧:
a=3
print(f'{"{"}{a}')
>>> {3
原因是,{}是.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")
如果性能不是问题,则获取完成的作业。
当您尝试插入代码字符串时,我建议使用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))
所以你不会像其他答案所暗示的那样被迫复制大括号
或者只是参数化括号本身?可能很冗长。
x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}')
print(x)
# {42}