我有输出,但是结构不正确
import mysql.connector
myconn=mysql.connector.connect(host='-----',user='developer',passwd='----',database='pos')
cur=myconn.cursor()
try:
cur.execute("select * from pos.tbl_store")
print('ID StoreID Name Type State')
for row in cur:
print('%d %s %s %s %s'%(row[0],row[1],row[2],row[3],row[4]))
except:
myconn.rollback()
myconn.close()
我得到这个
ID StoreID Name Type State
55 INAPHYD00036 MEDPLUS SAIDABAD 14 IN
58 INAPHYD00039 MEDPLUS DILSUKHNAGAR P&T COLONY 14 IN
64 INAPHYD00045 MEDPLUS MOTI NAGAR 14 IN
65 INAPHYD00046 MEDPLUS KPHB REMEDY HOSPITAL ROAD 14 IN
77 INAPHYD00058 MEDPLUS BOWENPALLY 14 IN
,预期结果是:
ID StoreID Name Type State
55 INAPHYD00036 MEDPLUS SAIDABAD 14 IN
58 INAPHYD00039 MEDPLUS DILSUKHNAGAR P&T COLONY 14 IN
64 INAPHYD00045 MEDPLUS MOTI NAGAR 14 IN
如何获得上面显示的预期结果?
答案 0 :(得分:3)
如果您可以安装第三方软件包,那么我建议tabulate
。在您的命令行中:
pip install tabulate
然后运行:
from tabulate import tabulate
headers = ['ID', 'StoreID', 'Name', 'Type', 'State']
formatted_table = tabulate(cur, headers=headers, tablefmt='plain')
print(formatted_table)
答案 1 :(得分:0)
例如,您可以使用右移板
h = ['ID', 'StoreID', 'Name', 'Type', 'State']
print(f'{h[0]:6}{h[1]:14}{h[2]:33}{h[3]:6}{h[4]:6}')
for row in cur:
print(f'{row[0]:6}{row[1]:14}{row[2]:33}{row[3]:6}{row[4]:6}')