0

I am struggling on a very simple thing.

I would like to print a string with a certain format:

import numpy as np
array = np.array([123.456789, 1.23456, 12.3456])
print("My First number is %3.4f, second %1.2f and third %2.9f" % array)

"array" is an numpy array and include the arguments (size: (1,3)) I'd like to print. But I am getting the following error message:

TypeError: only size-1 arrays can be converted to Python scalars

This works fine

array = (123.456789, 1.23456, 12.3456)
print("My First number is %3.4f, second %1.2f and third %2.9f" % array)

But I do have my data as an numpy array. Is there a simple way to convert the array to use the values as arguments for formatted printing pint()?

1
  • array = tuple(array) Just add this. Commented Nov 1, 2018 at 15:48

3 Answers 3

1

Pass to tuple:

print("My First number is %3.4f, second %1.2f and third %2.9f" % tuple(array))

Or use the new format

array = np.array([123.456789, 1.23456, 12.3456])
print("My First number is {:3.4f}, second {:1.2f} and third {:2.9f}".format(*array))
>> My First number is 123.4568, second 1.23 and third 12.345600000
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! The "new format" does best what I want.
0

the % formatter expects a tuple if there are multiple items to format into the string, this should fix it

 print("My First number is %3.4f, second %1.2f and third %2.9f" % (array[0],array[1],array[2]))

Comments

0

It is not working because both are not same object. that is the first array is numpy.ndarray

and second array which works is tuple.

so

in order to run the first numpy.ndarray try the following line

array1 = np.array([123.456789, 1.23456, 12.3456])

print("My First number is %3.4f, second %1.2f and third %2.9f" , array1[0], array1[1],array1[2])

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.