非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
原因是,{}是.format()的语法,因此在您的情况下.format)无法识别{Hello},因此引发了错误。
可以通过使用双花括号{{}}来覆盖它,
x = " {{ Hello }} {0} "
or
尝试%s进行文本格式化,
x = " { Hello } %s"
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))
所以你不会像其他答案所暗示的那样被迫复制大括号
如果只想打印一个大括号(例如{),可以使用{{,如果需要,可以稍后在字符串中添加更多大括号。例如:
>>> 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=“{{你好}}{0}”
或者只是参数化括号本身?可能很冗长。
x = '{open_bracket}42{close_bracket}'.format(open_bracket='{', close_bracket='}')
print(x)
# {42}
如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'