0

I'm having some data stored in the SQL database table. I need to fetch all that data from the DB and print it as a python output in a human-readable format like an aligned table.

Below you can see I used fetchall() method to fetch those data and used print statement with 2 for loops.

#executing all the records in the SQL query 
cursor.execute("SELECT * FROM game_log")

#Fetch results using fetchall() method
data=cursor.fetchall()

print("\n\nDate&Time\t\tName\tWord\tTurns Given\tTurns Used\tResults")

print("================================================================================")
for item in data:
    for value in item:
        print(value,end="\t")
    print()

Below you can see some of them are displaying as aligned but some of the data aren't displaying as aligned.

How to display all the data aligned?

enter image description here

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

0

Create a dataframe with Pandas from your data and then print it:

import pandas as pd

column_names = ["Date&Time", "Name", "Word", "Turns Given", "Turns Used", "Results"]
df = pd.DataFrame.from_records(data, columns = column_names)
print(df)
Tortar
  • 625
  • 5
  • 15
0

Use python f string with formatting like this:

>>> print(f'{2.2:10.2f}')
      2.20
>>> print(f'{2.2:10.1f}')
       2.2

check this for reference: https://docs.python.org/3/reference/lexical_analysis.html#f-strings

Tuhin Paul
  • 558
  • 4
  • 11
0

You can compute the maximum width of each column (including the widths of headings) and use a format string to ensure that all columns print the same width:

data = [ ["05/12/2021_20:12","kamal","football",8,8,"Lost"],
         ["05/12/2021_20:14","amal","australia",9,2,"Lost"]]

headings = ["Date&Time","Name","Word","Turns Given","Turns Used","Results"]
widths   = [max(map(len,map(str,col))) for col in zip(headings,*data)]

print(*(f"{c:<{w}}" for c,w in zip(headings,widths)))
print("="*sum(widths,len(widths)-1))
for row in data:
    print(*(f"{c:<{w}}" for c,w in zip(row,widths)))

Output:

Date&Time        Name  Word      Turns Given Turns Used Results
===============================================================
05/12/2021_20:12 kamal football  8           8          Lost   
05/12/2021_20:14 amal  australia 9           2          Lost 
Alain T.
  • 40,517
  • 4
  • 31
  • 51