2012-10-25 38 views
0

我正在從MySQL數據庫中讀取數據並希望將其打印到屏幕上。python tuple中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 

我怎樣才能使它左對齊?

回答

1

假設你只需要對準的最後一列,像這樣做:

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

- -sign它證明到左邊。

+0

非常感謝,我想得到每一行的理由 – user1773219

+0

@ user1773219請把結果通緝的問題。在評論中,格式化會丟失。 – ovgolovin

+0

非常感謝。我很抱歉,我不能清楚地表達這個問題。我認爲這個答案很棒('{row [0]:20} {row [1]:20} {row [2]:20} {row [3]:20}'。format(row = row)) – user1773219

0

另外,Python中有a new formatting syntax

據我所知,你希望每列都有相同的縮進。這可以通過指定每列應該佔據的空間來實現。因爲現在前3個字符串儘可能少地使用目標字符串,並且只有最後一個字符串需要20個符號。如果你指定每個字符串的長度,你將得到結果字符串中的輸出很好地對齊。

嘗試這種情況:

print('{row[0]:20}{row[1]:20}{row[2]:20}{row[3]:20}'.format(row=row)) 

的數字20在大括號表示各字段的長度。

+0

謝謝,我希望每一行都是justfiled。 – user1773219

+0

@ user1773219請顯示您想要的輸出示例。在問題中顯示此示例(單擊'edit')並添加此示例。 – ovgolovin

+0

非常感謝。你的回答非常好。 – user1773219