'Formatting numbers with same width using f-strings python

I want to format array of numbers with same width using f-strings. Numbers can be both positive or negative.

Minimum working example

import numpy as np  
arr = np.random.rand(10) - 0.5 
for num in arr:
    print(f"{num:0.4f}")

The result is

0.0647
-0.2608
-0.2724
0.2642
0.0429
0.1461
-0.3285
-0.3914

Due to the negative sign, the numbers are not printed off with the same width, which is annoying. How can I get the same width using f-strings?

One way that I can think of is converting number to strings and print string. But is there a better way than that?

for num in a: 
    str_ = f"{num:0.4f}" 
    print(f"{str_:>10}")


Solution 1:[1]

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.

Solution 2:[2]

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'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2