0

I want to convert a numpy array to a string representation and I am having issues when the number of digits in the numpy array is not constant. Consider the two cases -

import numpy as np

arr = np.array([0,0])
arr_str = str(arr).strip("[]")
print("String:", arr_str)
print("Len:", len(arr_str))

arr = np.array([10,0])
arr_str = str(arr).strip("[]")
print("String:", arr_str)
print("Len:", len(arr_str))
 

The output from this is -

String: 0 0
Len: 3
String: 10  0
Len: 5

The first case has the two digits separated by a single space while the second one has two spaces. The length of the second string should have been 4 and not 5 if it wasn't for the extra space. Is there any way to convert numpy to string so that every element is consistently separated by a single space?

This was with python 3.8 and numpy 1.19.2

2 Answers 2

1

You've done most of the work already. Now simply split the string and re-join it with single spaces:

num_list = arr_string.split()
print(' '.join(num_list))
Sign up to request clarification or add additional context in comments.

Comments

0

I am confused. Numpy is consistently separating them. Numpy identified that your data consisted of two digit data. As such, it provided two characters of space for every entry. How else would you have wanted numpy to do it? Take for example,

x = np.array([[10,0],[20,30]])

Would you want the first row to be 4 characters and the second to be 5 characters? That would look quite strange.

1 Comment

I guess it depends on your application, the downstream code was assuming that each entry would be separated by single space which was breaking things. I agree that it's not the best use of numpy.

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.