Uma*_*pta 5 python python-3.x f-string
我想使用f字符串格式化具有相同宽度的数字数组。数字可以是正数或负数。
最低工作示例
import numpy as np
arr = np.random.rand(10) - 0.5
for num in arr:
print(f"{num:0.4f}")
Run Code Online (Sandbox Code Playgroud)
结果是
0.0647
-0.2608
-0.2724
0.2642
0.0429
0.1461
-0.3285
-0.3914
Run Code Online (Sandbox Code Playgroud)
由于带有负号,因此无法以相同的宽度打印数字,这很烦人。如何使用F弦获得相同的宽度?
我能想到的一种方法是将数字转换为字符串并打印字符串。但是有没有比这更好的方法了?
for num in a:
str_ = f"{num:0.4f}"
print(f"{str_:>10}")
Run Code Online (Sandbox Code Playgroud)
在格式字符串前使用空格:
>>> f"{5: 0.4f}"
' 5.0000'
>>> f"{-5: 0.4f}"
'-5.0000'
Run Code Online (Sandbox Code Playgroud)
或加号(+)强制显示所有标志:
>>> f"{5:+0.4f}"
'+5.0000'
Run Code Online (Sandbox Code Playgroud)
您可以使用符号 格式选项:
>>> import numpy as np
>>> arr = np.random.rand(10) - 0.5
>>> for num in arr:
... print(f'{num: .4f}') # note the leading space in the format specifier
...
0.1715
0.2838
-0.4955
0.4053
-0.3658
-0.2097
0.4535
-0.3285
-0.2264
-0.0057
Run Code Online (Sandbox Code Playgroud)
引用文档:
该标志的选择是仅适用于数字类型,可以是下列情况之一:
Run Code Online (Sandbox Code Playgroud)Option Meaning '+' indicates that a sign should be used for both positive as well as negative numbers. '-' indicates that a sign should be used only for negative numbers (this is the default behavior). space indicates that a leading space should be used on positive numbers, and a minus sign on negative numbers.