python - 在 python 元组中格式化来自 mysql 的数据

标签 python mysql tuples

我正在从 MySQL 数据库读取数据并希望将其打印到屏幕上。

我使用:

import MySQLdb
conn = MySQLdb.connect(host='localhost',user='root',passwd='passwd',db='test',charset='utf8')
cursor = conn.cursor()
cursor.execute('select cust_name,cust_address,cust_city,cust_state from Customers')
numrows = int(cursor.rowcount)
for i in range(numrows):
    row =  cursor.fetchone()
    print "%s  %s  %s   %20s" %(row[0],row[1],row[2],row[3])
cursor.close()
conn.close()

结果是这样的:

Village Toys  200 Maple Lane  Detroit            MI

Kids Place  333 South Lake Drive  Columbus                     OH

Fun4All  1 Sunny Place  Muncie                     IN

Fun4All  829 Riverside Drive  Phoenix                     AZ

The Toy Store  4545 53rd Street  Chicago                     IL

如何使其左对齐?

最佳答案

假设您只想对齐最后一列,请这样做:

print "%s  %s  %s   %-20s" %(row[0],row[1],row[2],row[3])

--符号将其向左对齐。

关于python - 在 python 元组中格式化来自 mysql 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13062934/

相关文章:

python - 图像方向(python+openCV)

python - 有没有办法拉伸(stretch)整个显示图像以适应给定的分辨率?

带计数和行的 MySQL 查询

MySQL:字段中的空白字符实际上不是空白。它是什么?

Python 在列表中的元组中查找最大值、平均值、最小值和相加值

c# - "if (object is (string, Color))"c# 7.0 元组用法不起作用

python - 字典的值列表

MySQL 将两个表连接到 n :m Relation

python - string.join 使用元组或列表更快吗?

python - Google App Engine 进程已终止(错误代码 123)