Home > Software design >  Seperating list Items with a special character
Seperating list Items with a special character

Time:12-03

I have a list that I need to separate with a | character, but I don't know how to make it so that the character doesn't appear after the last item in each line.

The current project looks like this:

user_input = input()
lines = user_input.split(",")
mult_table = [[int(num) for num in line.split()] for line in lines]

for row in mult_table:
    for cell in row:
        print(cell, end=' | ')
    print()

The output:

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

The goal is to remove the last row of pipes. I'm rather new to python and programming in general so any help would be appreciated, Thanks!

CodePudding user response:

You can use join:

data = '1 2 3,4 5 6,7 8 9'
for line in data.split(','):
    print(' | '.join(line.split()))

# 1 | 2 | 3
# 4 | 5 | 6
# 7 | 8 | 9

Alternatively, print with sep parameter (note the unpacking operator *):

for line in data.split(','):
    print(*line.split(), sep=' | ')
  • Related