Home > Software design >  How do I remove the last comma from the output
How do I remove the last comma from the output

Time:10-01

n=3
result=[[1,2,3],[4,5,6],[7,8,9]]
for i in range(n):
    for j in range(n):
        print(result[i][j],end=',')
    print()

output: 1,2,3,
4,5,6,
7,8,9,

I'm getting the outputs I want, but how do i remove the last comma?

CodePudding user response:

Here is a nice concise solution using a list comprehension:

result = [[1,2,3],[4,5,6],[7,8,9]]
for r in result:
    print(','.join([str(x) for x in r]))

This prints:

1,2,3
4,5,6
7,8,9

CodePudding user response:

A much easier approach:

result = [[1,2,3],[4,5,6],[7,8,9]]

for r in result:
    print(*r, sep=',')

CodePudding user response:

you could print the first one alone, then in a loop, print the rest with a comma to the left:

result=[[1,2,3],[4,5,6],[7,8,9]]
for i in result:
    print(i[0], end='')
    for j in range(1, len(i)):
        print(","   str(i[j]), end='')
    print("")

CodePudding user response:

I prefer one-liners with str.join:

>>> print(*(','.join(map(str, i)) for i in result), sep='\n')
1,2,3
4,5,6
7,8,9
>>> 

Or:

>>> '\n'.join([','.join(map(str, i)) for i in result])
1,2,3
4,5,6
7,8,9
>>> 

CodePudding user response:

You can achieve that using Ternary operators.

n=3
result=[[1,2,3],[4,5,6],[7,8,9]]
for i in range(n):
    for j in range(n):
        print(result[i][j],end=',' if j %3 < 2 else '\n')

This will print

1,2,3
4,5,6
7,8,9
  • Related