12

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}")

3 Answers 3

17

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'
Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

0

In Python3 (at least 3.11.2) the format is attained by just adding enough space:

from numpy import arange

def f1(x):
     return((x**2)-(4*x)+9)

for i in arange(-1,1,0.1):
    print( print(f"{i:5.2f}\t{f1(i):7.2f}")

Being the result:

-1.00 14.00 -0.90 13.41 -0.80 12.84 -0.70 12.29 -0.60 11.76 -0.50 11.25 -0.40 10.76 -0.30 10.29 -0.20 9.84 -0.10 9.41 -0.00 9.00 0.10 8.61 0.20 8.24 0.30 7.89 0.40 7.56 0.50 7.25 0.60 6.96 0.70 6.69 0.80 6.44 0.90 6.21

The first digit before the point defines the spaces, thus 5 would be enough to hold 2 decimals, the minus or a space and the dot. For more decimals you would need to adjust the first number correspondingly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.