Search code examples
numpyintpretty-print

Print int numpy array with distance


I would like to print int numpy.ndrray with certain distance between elements. For example, for

a = np.array([2, 0, -1, -5, 3, 4])
print('a : {}'.format(a))

I have a : [ 2 0 -1 -5 3 4]

How can I get, for example a : [ 2 0 -1 -5 3 4]?


Solution

  • You can do this with formatting.

    a = np.array([2, 0, -1, -5, 3, 4])
    print(("a :" + " {:>3}"*len(a)).format(*a))
    a :   2   0  -1  -5   3   4
    

    The trick is to keep fixed portions separate, then replicate the {} portion by the number of elements in the array. The *a will pass on the necessary elements to the format string. If you really need the square braces it just gets a bit uglier.

    print(("a : [" + " {:>3}"*len(a) + "]").format(*a))
    a : [   2   0  -1  -5   3   4]