非工作示例:

print(" \{ Hello \} {0} ".format(42))

所需输出:

 {Hello} 42 

当前回答

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“{号码}”“{感谢所有的鱼}”)

其他回答

您需要将{{和}}加倍:

>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '

以下是Python文档中有关格式字符串语法的相关部分:

格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文字文本,并将其原样复制到输出中。如果需要在文字文本中包含大括号字符,可以通过加倍:{{和}}对其进行转义。

尝试这样做:

x = " {{ Hello }} {0} "
print x.format(42)

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'{{ 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'

如果在可以格式化的f-string模板中需要大括号,则需要在f-string的一组大括号中输出包含两个大括号的字符串:

css_template = f"{{tag}} {'{{'} margin: 0; padding: 0;{'}}'}"
for_p = css_template.format(tag="p")
# 'p { margin: 0; padding: 0;}'