With python3.8, a new feature is self documenting format strings. Where one would normally do this:
>>> x = 10.583005244
>>> print(f"x={x}")
x=10.583005244
>>>
现在,人们可以做到这一点,而减少了重复:
>>> x = 10.583005244
>>> print(f"{x=}")
x=10.583005244
>>>
这对于一个行字符串表示形式非常有效。但请考虑以下情形:
>>> 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 ]])
>>>
在这里,第一行没有对齐,这(可能)是不希望的。我更喜欢以下输出:
>>> import numpy as np
>>> some_fairly_long_named_arr = np.random.rand(4,2)
>>> print(f"some_fairly_long_named_arr=\n{some_fairly_long_named_arr!r}")
some_fairly_long_named_arr=
array([[0.06278696, 0.04521056],
[0.33805303, 0.17155518],
[0.9228059 , 0.58935207],
[0.80180669, 0.54939958]])
>>>
此处,输出的第一行也已对齐,但是它达到了在print语句中不重复两次变量名的目的。
因此,我的问题是:在自记录字符串中,是否可以在=符号后插入换行符?
我试图这样添加它,但是它不起作用:
>>> print(f"{some_fairly_long_named_arr=\n}")
SyntaxError: f-string expression part cannot include a backslash
I read the docs on format-specification-mini-language, but most of the formatting there only works for simple data types like integers, and I was not able to achieve what I wanted using those that work.
很抱歉写了这么长时间。