>…" />

我怎样才能打印文字大括号字符在python字符串,也使用 format呢?


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

给我:关键错误:Hello \
我想打印输出:{你好} 42

您需要将加倍

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

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

Format strings contain a€œreplacement fieldsa€ 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: .

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

例如:

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

未经作者同意,本文严禁转载,违者必究!