lcolhead = ['ID', 'Name', 'Email']
lrow1 = [1, 'Jane Doe', '[email protected]']
lrow2 = [2, 'Jake Doe', '[email protected]']
lrow3 = [3, 'Jane Fox', '[email protected]']
ltable1 = [lcolhead, lrow1, lrow2, lrow3]
for row in ltable1:
for item in row:
print(item, end=' | ')
output is each value on a single line separated by ' | '
ID | Name | Email | 1 | Jane Doe | [email protected] | 2 | John Doe | [email protected]...
I want it to print:
ID | Name | Email |
1 | Jane Doe | [email protected] |
2 | John Doe | [email protected] |
storing the column headers as a list as well as the row values in a list of lists but cannot figure out why it prints everything to a single line.
CodePudding user response:
Using your solution, adding a simple print()
statement in the outer loop fixes it:
lcolhead = ['ID', 'Name', 'Email']
lrow1 = [1, 'Jane Doe', '[email protected]']
lrow2 = [2, 'Jake Doe', '[email protected]']
lrow3 = [3, 'Jane Fox', '[email protected]']
ltable1 = [lcolhead, lrow1, lrow2, lrow3]
for row in ltable1:
for item in row:
print(item, end=' | ')
print() # printing nothing, followed by default end='\n'
To other programmers that may be a confusing use of end
though, so perhaps a better solution would be this:
for row in ltable1:
print(' | '.join(map(str, row)) ' | ')
This turns everything in row
into a string with map(str, ..)
and then joins those strings together with |
, adding a ' | '
at the end as well, for the same result (because no end
is specified, it defaults to \n
here).
The result in either case:
ID | Name | Email |
1 | Jane Doe | [email protected] |
2 | Jake Doe | [email protected] |
3 | Jane Fox | [email protected] |
Of course, if you don't even need that dangling ' | '
, you can just:
for row in ltable1:
print(' | '.join(map(str, row)))
CodePudding user response:
for row in ltable1:
print( " | ".join( row) " | ")
But I'm questioning the utility of the last vertical bar.