非工作示例:
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))
其他回答
试试看:
x=“{{你好}}{0}”
f-string(python 3)
通过只对字符串中要应用f-magic的部分使用f-string,并对所有文字和可能包含“不安全”特殊字符的部分使用常规(哑)字符串,可以避免使用双括号。让python简单地通过将多个字符串堆叠在一起来完成字符串连接。
number = 42
print(" { Hello }"
f" {number} "
"{ thanks for all the fish }")
### OUTPUT:
{ Hello } 42 { thanks for all the fish }
注意:字符串之间不需要换行符。我只是为了可读性而添加了它们。您还可以编写上面的代码,如下所示:⚠️ 警告:这可能会伤害你的眼睛或使你头晕!打印(“{你好}”f“{号码}”“{感谢所有的鱼}”)
您想用字符{或}格式化字符串
你只需要把它们加倍。
格式{带有f“{{”,}带有f‘}}”
So :
name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
输出:
你好,鲍勃!我想打印}和{或{}
对于确切的示例,OR:
number = 42
print(f'{{Hello}} {number}')
将打印:
{你好}42
如果要仅打印大括号的一侧:
a=3
print(f'{"{"}{a}')
>>> {3
如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'