在 python3.8 中,一个新功能是自记录格式字符串。人们通常会这样做:
>>> x = 10.583005244
>>> print(f"x={x}")
x=10.583005244
Run Code Online (Sandbox Code Playgroud)
现在可以减少重复次数来做到这一点:
>>> x = 10.583005244
>>> print(f"{x=}")
x=10.583005244
Run Code Online (Sandbox Code Playgroud)
这对于单行字符串表示非常有效。但请考虑以下场景:
>>> import numpy as np
>>> some_fairly_long_named_arr = np.random.rand(4,2)
>>> print(f"{some_fairly_long_named_arr=}")
some_fairly_long_named_arr=array([[0.05281443, 0.06559171],
[0.13017109, 0.69505908],
[0.60807431, 0.58159127],
[0.92113252, 0.4950851 ]])
Run Code Online (Sandbox Code Playgroud)
在这里,第一行没有对齐,这(可以说)是不可取的。我更喜欢以下输出:
>>> print(f"some_fairly_long_named_arr=\n{some_fairly_long_named_arr!r}")
some_fairly_long_named_arr=
array([[0.05281443, 0.06559171],
[0.13017109, 0.69505908],
[0.60807431, 0.58159127],
[0.92113252, 0.4950851 ]])
Run Code Online (Sandbox Code Playgroud)
在这里,输出的第一行也对齐了,但是它违背了在 print 语句中不重复变量名称两次的目的。
该示例是一个 numpy 数组,但它也可能是一个 pandas 数据框等。
=因此,我的问题是:可以在自记录字符串的符号后面插入换行符吗?
我尝试像这样添加它,但它不起作用:
>>> print(f"{some_fairly_long_named_arr=\n}")
SyntaxError: f-string expression part cannot include a backslash
Run Code Online (Sandbox Code Playgroud)
我阅读了format-specation-mini-language 上的文档,但其中的大多数格式仅适用于整数等简单数据类型,并且我无法使用那些有效的数据类型来实现我想要的效果。