非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
虽然不是更好,但仅供参考,您也可以这样做:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
例如,当有人想要打印{argument}时,它会很有用。它可能比“{{}}”更可读。format(“argument”)
注意,在Python 2.7之后省略了参数位置(例如{}而不是{0})
其他回答
试试看:
x=“{{你好}}{0}”
如果你要经常这样做,最好定义一个实用函数,让你使用任意的大括号替代,比如
def custom_format(string, brackets, *args, **kwargs):
if len(brackets) != 2:
raise ValueError('Expected two brackets. Got {}.'.format(len(brackets)))
padded = string.replace('{', '{{').replace('}', '}}')
substituted = padded.replace(brackets[0], '{').replace(brackets[1], '}')
formatted = substituted.format(*args, **kwargs)
return formatted
>>> custom_format('{{[cmd]} process 1}', brackets='[]', cmd='firefox.exe')
'{{firefox.exe} process 1}'
注意,这将在括号是长度为2的字符串或两个字符串的可迭代(对于多字符分隔符)的情况下工作。
我在尝试打印文本时遇到了这个问题,我可以将文本复制粘贴到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))
你可以通过加倍牙套来逃避。
Eg:
x = "{{ Hello }} {0}"
print(x.format(42))
您可以使用“引号墙”将格式化字符串部分与常规字符串部分分开。
发件人:
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}