无法工作的示例:
print(" \{ Hello \} {0} ".format(42))
期望得到的输出:
{Hello} 42
无法工作的示例:
print(" \{ Hello \} {0} ".format(42))
期望得到的输出:
{Hello} 42
您需要将{{
和}}
加倍:
>>> x = " {{ Hello }} {0} "
>>> print(x.format(42))
' { Hello } 42 '
格式化字符串包含用大括号
{}
括起来的“替换字段”。不在大括号中的任何内容都被视为文本,将不加修改地复制到输出中。如果需要在文本中包含大括号字符,则可以通过两次输入来转义:{{
和}}
。
"{ something { } {value}".format(42)
是不能正常工作的。 - AJP{0}
参照的是 .format()
中的第一个参数。只要在 .format()
中提供相同数量的参数,就可以像 {0} {1} {2}
这样打印多个值。请参考http://docs.python.org/library/string.html#format-examples获取更多示例。 - Greg Hewgillmy_greet = "HELLO"
,你可以使用仅有的两组大括号,通过 print(f"{ {my_greet.lower()} }")
得到 {hello}
作为输出。在大括号之间留一个空格即可。 - yrnrstr.format()
而不是 f-strings,它们不是相互兼容的。 - wjandrea你可以通过将大括号翻倍来转义它。
例如:
x = "{{ Hello }} {0}"
print(x.format(42))
您想使用字符 {
或 }
格式化字符串
您只需要将它们加倍。
使用 f'{{'
格式化 {
,使用 f'}}'
格式化 }
因此:
name = "bob"
print(f'Hello {name} ! I want to print }} and {{ or {{ }}')
输出:
你好,Bob!我想要打印 } 和 { 或 { }
或者精确的例子:
number = 42
print(f'{{Hello}} {number}')
将打印:
{你好} 42
最后:
number = 42
string = "bob"
print(f'{{Hello}} {{{number}}} {number} {{{string}}} {string} ')
{你好} {42} 42 {鲍勃} 鲍勃
原评论如下:
我试图为某些目的格式化一个小JSON,像这样:
'{"all": false, "selected": "{}"}'.format(data)
以获得类似于{"all": false, "selected": "1,2"}
的东西。
在处理JSON时,经常会遇到“转义大括号”的问题。
我的建议是:
import json
data = "1,2"
mydict = {"all": "false", "selected": data}
json.dumps(mydict)
它比另一种选择更清洁,那个选择是:
'{{"all": false, "selected": "{}"}}'.format(data)
当 JSON 字符串变得比示例更复杂时,使用 json
库是绝对可取的。
data = 'foo"'
,那么另一种选择也是非常错误的,因为 data
值中的 "
无法被正确转义。 - chepner尝试这样写:
x = "{{ 你好 }} {0}"
试着这样做:
x = " {{ Hello }} {0} "
print x.format(42)
虽然并没有更好,只是供参考,你也可以这样做:
>>> x = '{}Hello{} {}'
>>> print x.format('{','}',42)
{Hello} 42
例如,当有人想要打印{argument}
时,这很有用。它可能比'{{{}}}'.format('argument')
更易读。
请注意,在Python 2.7之后省略参数位置(例如{}
而不是{0}
)。
key = "FOOBAR"
print(f"hello {{{key}}}")
输出
hello {FOOBAR}
如果有人想使用f字符串打印花括号内的内容。
你可以使用 f-strings 来避免在字符串中使用双花括号,只需将 f-strings 仅应用于希望应用 f-魔法的字符串部分,并对所有字面值和可能包含“不安全”特殊字符的内容使用常规(愚蠢的)字符串。通过将多个字符串堆叠在一起,让 Python 来进行字符串连接。
number = 42
print(" { Hello }"
f" {number} "
"{ thanks for all the fish }")
### OUTPUT:
{ Hello } 42 { thanks for all the fish }
NOTE: Line breaks between the strings are NOT required. I have only added them for readability. You could as well write the code above as shown below:
⚠️ WARNING: This might hurt your eyes or make you dizzy!
print("{Hello}"f"{number}""{thanks for all the fish}")
{{ }}
) 的人可以使用string.Template
。在那里,您可以替换形式为$foo
的标识符(方便生成 LaTeX 代码)。 - 0 _