0

am practicing python I have this issue here, I have a list of three teams,teams = ['manu','spurs','roma'] just looping through the index 0 i was able to print the outcome

teams = ['manu','spurs','roma']
for m in teams[0]:
    print(m,'\t')

` but can I print all the teams in a tabula form like see image

help out

cipher
  • 373
  • 7
  • 20

3 Answers3

1

You can try to do it something like this. Print letter by letter in for loops with try/except block. Use print(end='\n') to create new line after printed all letters from index 'x'. (You can write print() without end='\n' but it will be less understandable.

teams = ['manu','spurs','roma']
for x in range(len(max(teams, key=len))):
    for m in teams:
        try:
            print(m[x], end='\t')
        except IndexError:
            print("", end='\t')
    print(end='\n')
K.Oleksy
  • 155
  • 1
  • 9
  • This prints everything in one line. Add print('\n') at the end of the loop – IoaTzimas Oct 08 '20 at 14:02
  • this works but i just don't understand the print() at the end any explanation – cipher Oct 08 '20 at 14:08
  • I added `print()` to create a new line after the printed letter 'x' form all words. I will try to modify it to create more efficient code and edit post after that. – K.Oleksy Oct 08 '20 at 14:16
0

Is your data fixed? Cause if not maybe you already know on how to get those data you have and put it in the loop. Anyways this might help you.

teams = ['manu','spurs','roma']
for m,s,r in zip(teams[0],teams[1],teams[2]):
    print(m,s,r,'\t')

--UPDATE---

I always felt I've seen this before... so luckily I've found it and you can have it this way if you want. Thanks to this

from itertools import zip_longest

teams = ['manu','spurs','roma']
text=' '.join(teams)

for x in zip_longest(*text.split(), fillvalue=' '):
    print ('\t'.join(x))
Ice Bear
  • 2,676
  • 1
  • 8
  • 24
0

The repsponse of K.Oleksy is great but uses the exceptions to catch the end of the string. I'll juste show you how to avoid that as Exceptions are not made for that.

teams = ['nusqdgqsdgsq','spjurs','romaaa']

max_lenght = len(max(teams, key = len))
print(max_lenght)
for i in range(max_lenght):
    for team_index in range(len(teams)):
        if (i < len(teams[team_index])):
            print(teams[team_index][i], end = '\t')
        else:
            print('  ', end = '')
    print()
Amiral ASTERO
  • 365
  • 1
  • 6