Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Seperating list Items with a special character

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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=' | ')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading