Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}")
like image 406
Umang Gupta Avatar asked May 04 '19 17:05

Umang Gupta


People also ask

How do you use %d and %f in Python?

The formatting using % is similar to that of 'printf' in C programming language. %d – integer %f – float %s – string %x – hexadecimal %o – octal The below example describes the use of formatting using % in Python.

What is f {} in Python?

The f-string was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast. Example: The f or F in front of strings tells Python to look at the values inside {} and substitute them with the values of the variables if exist.

What does %d and %S mean in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))


2 Answers

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'
like image 69
ForceBru Avatar answered Sep 27 '22 15:09

ForceBru


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.
like image 33
Eugene Yarmash Avatar answered Sep 27 '22 16:09

Eugene Yarmash