非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
我在尝试打印文本时遇到了这个问题,我可以将文本复制粘贴到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))
其他回答
您可以使用“引号墙”将格式化字符串部分与常规字符串部分分开。
发件人:
print(f"{Hello} {42}")
to
print("{Hello}"f" {42}")
一个更清楚的例子是
string = 10
print(f"{string} {word}")
输出:
NameError: name 'word' is not defined
现在,添加报价墙,如下所示:
string = 10
print(f"{string}"" {word}")
输出:
10 {word}
当您尝试插入代码字符串时,我建议使用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 = " {{ Hello }} {0} "
print x.format(42)
您需要将{{和}}加倍:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
以下是Python文档中有关格式字符串语法的相关部分:
格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文字文本,并将其原样复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{和}}对其进行转义。
您想用字符{或}格式化字符串
你只需要把它们加倍。
格式{带有f“{{”,}带有f‘}}”
So :
name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
输出:
你好,鲍勃!我想打印}和{或{}
对于确切的示例,OR:
number = 42
print(f'{{Hello}} {number}')
将打印:
{你好}42