merkle
merkle

Reputation: 1815

Remove trailing spaces of an array

I have a 2D array. While printing I want to remove the trailing spaces at the end of each row.

A = [[ 1,2,3 ,4 ,5],
 [16,17,18,19,6],
 [15,24,25,20,7],
 [14,23,22,21,8],
 [13,12,11,10,9]]

for i in range(len(A)):
    for j in range(len(A)):
        print(A[i][j], end = ' ')
    print()

My test case are failing because of trailing space. Can anyone tell me where the mistake is?

Upvotes: 2

Views: 119

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51653

You print your spaces yourself by using

print(A[i][j], end= ' ')
               ^^^^^^^^

I would suggest doing

A = [[ 1,2,3 ,4 ,5],
     [16,17,18,19,6],
     [15,24,25,20,7],
     [14,23,22,21,8],
     [13,12,11,10,9]]

for inner in A:
    print(*inner)

Output:

1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9

without any trailing spaces.

Upvotes: 1

Related Questions