使用 f 字符串格式化具有相同宽度的数字 python
Formatting numbers with same width using f-strings python
我想使用 f 字符串格式化具有相同宽度的数字数组。数字可以是正数也可以是负数。
最小工作示例
import numpy as np
arr = np.random.rand(10) - 0.5
for num in arr:
print(f"{num:0.4f}")
结果是
0.0647
-0.2608
-0.2724
0.2642
0.0429
0.1461
-0.3285
-0.3914
由于负号,数字没有以相同的宽度打印出来,这很烦人。如何使用 f-strings 获得相同的宽度?
我能想到的一种方法是将数字转换为字符串并打印字符串。但是还有比这更好的方法吗?
for num in a:
str_ = f"{num:0.4f}"
print(f"{str_:>10}")
在格式规范之前使用space:
# v-- here
>>> f"{5: 0.4f}"
' 5.0000'
>>> f"{-5: 0.4f}"
'-5.0000'
或加号(+
)强制显示所有个符号:
>>> f"{5:+0.4f}"
'+5.0000'
您可以使用符号 formatting选项:
>>> 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
引用文档:
The sign option is only valid for number types, and can be one of the
following:
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.
我想使用 f 字符串格式化具有相同宽度的数字数组。数字可以是正数也可以是负数。
最小工作示例
import numpy as np
arr = np.random.rand(10) - 0.5
for num in arr:
print(f"{num:0.4f}")
结果是
0.0647
-0.2608
-0.2724
0.2642
0.0429
0.1461
-0.3285
-0.3914
由于负号,数字没有以相同的宽度打印出来,这很烦人。如何使用 f-strings 获得相同的宽度?
我能想到的一种方法是将数字转换为字符串并打印字符串。但是还有比这更好的方法吗?
for num in a:
str_ = f"{num:0.4f}"
print(f"{str_:>10}")
在格式规范之前使用space:
# v-- here
>>> f"{5: 0.4f}"
' 5.0000'
>>> f"{-5: 0.4f}"
'-5.0000'
或加号(+
)强制显示所有个符号:
>>> f"{5:+0.4f}"
'+5.0000'
您可以使用符号 formatting选项:
>>> 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
引用文档:
The sign option is only valid for number types, and can be one of the following:
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.