我想以更好的格式打印数据库中的数据,这是我制作的游戏。这是代码:
def read_all_tables(self):
self.cursor.execute('SELECT Name, Gender, Age, Score, Date, Time FROM Link JOIN Scores ON Score_ID = Scores.ID JOIN Player ON Player_ID = Player.id ORDER BY Score DESC')
Data = self.cursor.fetchall()
for Row in Data:
print()
for record in range(len(Row)):
print(Row[record], end=" ")
输出为:
HAMMAD MALE 18 900 07/01/18 13:07:02
HAMMAD MALE 18 850 07/01/18 13:30:11
INDERVEER MALE 18 750 07/01/18 13:35:46
HAMMAD MALE 18 500 07/01/18 13:08:29
HAMMAD MALE 18 400 07/01/18 14:07:29
PARSA MALE 18 300 07/01/18 13:36:58
HADIA FEMALE 19 300 07/01/18 14:09:37
MANAAL FEMALE 18 100 07/01/18 13:51:40
MICHAL MALE 18 0 07/01/18 13:42:41
HAMMAD MALE 18 0 07/01/18 13:44:04
HADIA FEMALE 19 0 07/01/18 13:45:51
MANAAL FEMALE 18 0 07/01/18 13:53:02
JACK WEIRD 21 0 07/01/18 13:53:49
HAMMAD MALE 18 0 07/01/18 13:54:44
HAMMAD MALE 18 0 07/01/18 13:56:08
MANAAL FEMALE 18 0 07/01/18 13:57:39
PARSA MALE 18 0 07/01/18 13:58:25
HAMMAD MALE 18 0 07/01/18 13:59:08
HAMMAD MALE 18 0 07/01/18 14:10:37
如何对齐它们并设置列标题?我不想使用任何图书馆。
使用字符串格式化功能:
formatted_row = '{:<10} {:<6} {:>6} {:>6} {:<9} {:<9}'
print(formatted_row.format("Name", "Gender", "Age", "Score", "Date", "Time"))
for Row in Data:
print(formatted_row.format(*Row))
输出:
Name Gender Age Score Date Time
HAMMAD MALE 18 900 07/01/18 13:07:02
HAMMAD MALE 18 850 07/01/18 13:30:11
INDERVEER MALE 18 750 07/01/18 13:35:46
HAMMAD MALE 18 500 07/01/18 13:08:29
HAMMAD MALE 18 400 07/01/18 14:07:29
PARSA MALE 18 300 07/01/18 13:36:58
HADIA FEMALE 19 300 07/01/18 14:09:37
MANAAL FEMALE 18 100 07/01/18 13:51:40
...
在这种方法中,我们对列的宽度进行硬编码。为了动态调整列宽,我们将不得不做更多的工作。我希望这对你有用。
为了动态调整宽度,我们需要传递数据两次:第一次确定每列的最大宽度,第二次打印。
# Determine the longest width for each column
header = ("Name", "Gender", "Age", "Score", "Date", "Time")
widths = [len(cell) for cell in header]
for row in Data:
for i, cell in enumerate(row):
widths[i] = max(len(str(cell)), widths[i])
# Construct formatted row like before
formatted_row = ' '.join('{:%d}' % width for width in widths)
print('DEBUG: widths={!r}'.format(widths))
print('DEBUG: formatted_row={!r}'.format(formatted_row))
print(formatted_row.format(*header))
for row in Data:
print(formatted_row.format(*row))
输出:
DEBUG: widths=[9, 6, 3, 5, 8, 8]
DEBUG: formatted_row='{:9} {:6} {:3} {:5} {:8} {:8}'
Name Gender Age Score Date Time
HAMMAD MALE 18 900 07/01/18 13:07:02
HAMMAD MALE 18 850 07/01/18 13:30:11
INDERVEER MALE 18 750 07/01/18 13:35:46
...
一旦您对结果感到满意,您可以删除 DEBUG 行。他们在那里展示代码是如何工作的。
对于标题,只需选择您想要的文本,例如
select 'Name Gender Age ...';
要格式化数据,请使用 printf() 函数(请参阅 https://sqlite.org/lang_corefunc.html#printf),例如
select printf('%-20s %-6s %2d ....', Name, Gender, Age, ...) from ...;
(根据需要进行调整。)
接受的答案对我不起作用,所以我做了自己的类似答案。
将“结果”替换为“数据”。
记得添加row_factory,这样在执行select * table时,就可以使用标题,并将它们插入到表的顶行。这就是前 3 行所做的事情。
其余代码:
创建列长度列表,最初用 0 * 第一行项目数(也是标题)填充它们。
对于行中的每个单元格,如果单元格的宽度小于该列的最大宽度,则将最大值设置为当前单元格宽度。
打印每行中的单元格,用空格替换 None ,并添加偏移量。
cursor.row_factory = sqlite3.Row
result=cursor.execute( 'select rowlong as info,games,roms,disks,samples,roms_disks_samples as all_files from stats' ).fetchall()
result.insert( 0, (result[0].keys()) )#insert column names as first row (position 0); 'cursor.row_factory = sqlite3.Row' must be used before
int_offset = 2
ls_int_max_column_length = [0] * len( result[0] )
for row in result:
for i in range(len(row)):
int_cell_space = len( str( row[i] ) )
if ls_int_max_column_length[i] < int_cell_space:
ls_int_max_column_length[i] = int_cell_space
#print(ls_int_max_column_length)
print("")
for row in result:
for i in range(len(row)):
print ( str(row[i]).ljust( ls_int_max_column_length[i] + int_offset ).replace('None',' ') , end = " ")
#print ( str(row[i]) , end = " ")
print("")
print("")
你可以手动做,但不推荐,如果长度改变怎么办:
print("")
for row in result:
print ( str(row[0]).ljust(38), str(row[1]).ljust(25).replace('None',' '), str(row[2]).ljust(21).replace('None',' '), str(row[3]).ljust(16).replace('None',' '), str(row[4]).ljust(8).replace('None',' '), str(row[5]).ljust(9).replace('None',' '))
print("")