1

我正在使用字符串模板来打印cur.fetchall()来自 MySQL 数据库的漂亮数据。

一个典型的元组如下所示:

(('DL2C1683', 'in', datetime.datetime(2013, 4, 28, 15, 53, 27), 'hyundai i10', '11'), ('UP1S1783', 'in', datetime.datetime(2013, 4, 28, 15, 53, 57), 'honda kinetic', '11'))

我正在使用以下代码打印此元组:

template = "{0:15}|{1:15}|{2:15}|{3:15}|{4:15}" 
print template.format("Registration No.", "State", "Time", "Make", "Sector") # header
for row in rows: 
    print template.format(*row)

datetime 对象没有打印,我得到15,也在标题之后,下面的行没有正确对齐。

输出:

Registration No.|State          |Time           |Make           |Sector         
DL2C1683       |in             |15|hyundai i10    |11             
UP1S1783       |in             |15|honda kinetic  |11     
4

1 回答 1

3

使用更大的宽度,例如。25还要添加!s作为.format转换标志以强制datetime转换为str

import datetime
template = "{0:25}|{1:25}|{2!s:25}|{3:25}|{4:25}"
rows = (('DL2C1683', 'in', datetime.datetime(2013, 4, 28, 15, 53, 27), 'hyundai i10', '11'),
        ('UP1S1783', 'in', datetime.datetime(2013, 4, 28, 15, 53, 57), 'honda kinetic', '11'))
print template.format("Registration No.", "State", "Time", "Make", "Sector") # header
for row in rows: 
    print template.format(*row)

Registration No.         |State                    |Time                     |Make                     |Sector                   
DL2C1683                 |in                       |2013-04-28 15:53:27      |hyundai i10              |11                       
UP1S1783                 |in                       |2013-04-28 15:53:57      |honda kinetic            |11        
于 2013-04-28T11:28:25.733 回答