J. Park
J. Park

Reputation: 33

How to print array as specific format?

I have an array formatted like this:

[-22.99253267 -83.23210952  77.71126322  43.99377722 -41.75731176 89.02862477]

I would like to print this array to receive this result

[-22.992 -83.232  77.711  43.993 -41.757 89.028]

I know It will be a similar result if I use np.set_printoptions(precision=3), but I would like to know how to receive this result using 9.3f.

Upvotes: 3

Views: 16278

Answers (2)

PilouPili
PilouPili

Reputation: 2699

To print the data in column :

for data in x:
    print '{:9.3f}'.format(data)

or

To print the data in row : (don't forget import sys)

for data in x:
    sys.stdout.write('{:9.3f}'.format(data))

Upvotes: 4

Glazbee
Glazbee

Reputation: 648

Using String.format()

list = [-22.99253267, -83.23210952,  77.71126322,  43.99377722, -41.75731176, 89.02862477]
for numbers in list :
    print('{:9.3f}'.format(data))

I receive the output

-22.993
-83.232
 77.711
 43.994
-41.757
 89.029

EDIT

Following OP's comment, here's an update which would append all elements into a list.

y = []
list = [-22.99253267, -83.23210952,  77.71126322,  43.99377722, -41.75731176, 89.02862477]
for numbers in list:
   x = '{:9.3f}'.format(data)
   y.append(x)
print(y)

Output

['  -22.993', '  -83.232', '   77.711', '   43.994', '  -41.757', '   89.029']

Upvotes: 0

Related Questions