如何对齐 python 输出

How to align a python output

我在 SQL 数据库 table 中存储了一些数据。我需要从数据库中获取所有数据,并将其打印为 python 输出格式,以人类可读的格式输出,例如对齐的 table.

你可以在下面看到我使用 fetchall() 方法获取这些数据并使用 print 语句和 2 for 循环。

#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()

您可以在下面看到其中一些数据显示为对齐,但一些数据未显示为对齐。

如何显示所有数据对齐?

enter image description here

使用您的数据 Pandas 创建一个数据框,然后打印它:

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)

使用 python f 字符串,格式如下:

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

检查此以供参考:https://docs.python.org/3/reference/lexical_analysis.html#f-strings

您可以计算每列的最大宽度(包括标题的宽度)并使用格式字符串确保所有列打印相同的宽度:

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)))

输出:

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