非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
非工作示例:
print(" \{ Hello \} {0} ".format(42))
所需输出:
{Hello} 42
当前回答
您需要将{{和}}加倍:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
以下是Python文档中有关格式字符串语法的相关部分:
格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文字文本,并将其原样复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{和}}对其进行转义。
其他回答
我使用了双{{}}来防止fstring值注入,
例如,这里是我的Postgres UPDATE语句,用于更新整数数组列,该列采用表达式{}来捕获数组,即:
ports=“{100200300}”
使用fstrings,
ports = [1,2,3]
query = f"""
UPDATE table SET ports = '{{{ports}}}' WHERE id = 1
"""
实际查询语句将是,
UPDATE table SET ports = '{1,2,3}'
这是一个有效的延期
如果你要经常这样做,最好定义一个实用函数,让你使用任意的大括号替代,比如
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的字符串或两个字符串的可迭代(对于多字符分隔符)的情况下工作。
您可以使用“引号墙”将格式化字符串部分与常规字符串部分分开。
发件人:
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}
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“{号码}”“{感谢所有的鱼}”)
如果需要在字符串中保留两个大括号,则变量的每一侧都需要5个大括号。
>>> myvar = 'test'
>>> "{{{{{0}}}}}".format(myvar)
'{{test}}'