如何在字符串中打印文字curlybrace字符并在其上使用.format?

2024-05-21 04:08:31 发布

您现在位置:Python中文网/ 问答频道 /正文

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

给我:Key Error: Hello\\

我想打印输出:{Hello} 42


Tags: keyformathelloerrorprint打印输出
3条回答

您需要将{{}}加倍:

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

以下是Python documentation for format string syntax的相关部分:

Format strings contain “replacement fields” surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

你可以通过加倍大括号来逃避它

例如:

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

Python 3.6+(2017)

在Python的最新版本中,可以使用f-strings(另请参见PEP498

对于f字符串,应该使用双精度{{}}

n = 42  
print(f" {{Hello}} {n} ")

产生所需的结果

 {Hello} 42

如果需要解析括号中的表达式而不是使用文本,则需要三组括号:

hello = "HELLO"
print(f"{{{hello.lower()}}}")

产生

{hello}

相关问题 更多 >