Python如何填充mysql选项卡的输出

2024-09-25 02:27:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用print函数打印表中的每一行。你知道吗

select_stmt = "SELECT user,password FROM account"

mycursor.execute(select_stmt)
myresult = mycursor.fetchall()

for row in myresult:
    print (row)

目前它以随意的方式打印:

(None, 'A***9****')
(None, None)
('usertest', 'pwtest')

如何填充每一列,使其看起来更清晰?谢谢


Tags: 函数fromnoneexecuteaccountpasswordselectrow
3条回答

@JR ibkr@Willem Van Onsem我能够使用Willem的方法和JR的方法组合填充所有列:

select_stmt = "SELECT site, user,password, email1, email2, comment, date FROM account"
mycursor.execute(select_stmt)

myresult = mycursor.fetchall()

len_site = max(map(lambda x: len(str(x[0])), myresult))     #site
len_user = max(map(lambda x: len(str(x[0])), myresult))     #user
len_pw = max(map(lambda x: len(str(x[0])), myresult))       #pw
len_em1 = max(map(lambda x: len(str(x[0])), myresult))      #email1
len_em2 = max(map(lambda x: len(str(x[0])), myresult))      #email2
#len_com = max(map(lambda x: len(str(x[0])), myresult))     #comments (This did not pad correctly. It protruded into the dates column)
len_dt = max(map(lambda x: len(str(x[0])), myresult))       #date

for site, user, pwd, em1, em2, com, dt in myresult:

    print ('{} {} {} {} {} {:<65} {}'.format(str(site).ljust(len_site),
                        str(user).ljust(len_user), str(pwd).ljust(len_pw), str(em1).ljust(len_em1),
                        str(em2).ljust(len_em2), str(com), str(dt).ljust(len_dt)))

在正常情况下,你是对的,我可能不想打印所有列,但我这样做是为了学习严格。由于某些原因,注释列没有正确填充,所以我只是手动输入了最大长度65。不确定这是不是最有效的方法,我想听听你的看法。谢谢

在一个表中,正好有特定数量的列。最终,您不会在控制台中编写整个列。您只能在控制台中写入选定的信息。你知道吗

for user, pwd in myresult:
      print('{:>5} {:>5}'.format(user, pwd))

或者

for result in myresult:
      user = myresult['user']
      pwd = myresult['pwd']
      print('{:>5} {:>5}'.format(user, pwd))

有关更多信息,请签出https://docs.python.org/3.4/library/string.html#formatexamples。你知道吗

两列

如果这两列的字符数永远不会超过24个,您可以使用以下示例:

for user, pwd in myresult:
    print('{: <20} {}'.format(user, pwd))

或者如果事先不知道,我们可以首先确定第一列的最大大小:

len_user = max(map(lambda x: len(str(x[0])), myresult))
for user, pwd in myresult:
    print('{} {}'.format(str(user).ljust(len_user), pwd))

对于样本数据,这将产生:

>>> len_user = max(map(lambda x: len(str(x[0])), myresult))
>>> for user, pwd in myresult:
...     print('{} {}'.format(str(user).ljust(len_user), pwd))
... 
None     A***9****
None     None
usertest pwtest

您可以在格式中的两个{}之间添加更多间距,以增加元素之间的间距,例如:

>>> for user, pwd in myresult:
...     print('{}    {}'.format(str(user).ljust(len_user), pwd))
... 
None        A***9****
None        None
usertest    pwtest

多列

对于多列,我们可以按照相同的过程,使用numpy计算列最大值:

import numpy as np

lens = np.max([[len(str(xi)) for xi in x] for x in myresult], axis=0)
myformat = ' '.join(['{}']*len(lens))

for col in myresult:
    print(myformat.format(*map(str.ljust, map(str, col), lens)))

相关问题 更多 >