Formatting numbers with same width using f-strings python
Use a space before the format specification:
# v-- here
>>> f"{5: 0.4f}"
' 5.0000'
>>> f"{-5: 0.4f}"
'-5.0000'
Or a plus (+
) sign to force all signs to be displayed:
>>> f"{5:+0.4f}"
'+5.0000'
You can use the sign formatting option:
>>> 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
To quote the documentation:
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.