简体   繁体   中英

Uneven number of spaces when converting numpy to string

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

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM