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}")
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.
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.
%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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With