Jack Vincent
Jack Vincent

Reputation: 39

Python Print list on separate lines

I'm trying to print my leader board out however its printing it on one line instead of multiple.

So far this is my code:

cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()

topscore = list(topscore)

print(topscore)

And when it runs it outputs like this: [('VortexHD', 6), ('test', 0), ('TestOCR', 0)]

However i want it to output the names and score on separate lines like this:

VortexHD, 6

Test, 0

TestOCR, 0

any help is appreciated thank you.

Upvotes: 1

Views: 486

Answers (4)

Python has a predefined format if you use print(a_variable) then it will go to next line automatically.So, to get the required solution you need to print first element in tuple followed ',' and then second element by accessing with index number.

cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()  
topscore = list(topscore)

for value in topscore:
    print(value[0],',',value[1])

Upvotes: 0

ruohola
ruohola

Reputation: 24107

You can just loop over the output and print its every element. You don't have to create a list of the output first, since fetchall() returns a list already, so you can do it like this:

cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()

for username, score in topscore:  # this uses tuple unpacking
    print(username, score)

Output:

VortexHD, 6
Test, 0
TestOCR, 0

Upvotes: 0

Christopher_Okoro
Christopher_Okoro

Reputation: 389

cursor.execute('SELECT username, score FROM Players order by score DESC limit 5')
topscore = cursor.fetchall()

topscore = list(topscore)
for i in topscore:
    print(i[0],i[1],sep=' , ')
    print('\n')

Upvotes: 1

Cubimon
Cubimon

Reputation: 150

print automatically adds an endline, so just iterate and print each value seperately:

for score in topscore:
    print(score)

Upvotes: 2

Related Questions