2014-10-30 67 views
0

我遇到問題。我試圖在python中打印一系列列表以使其與垂直對齊。我的代碼是:如何在python中對齊字符串而不創建表格

def show(): 
    book = "data.txt" 
    f = open(book,'r') 
    line = f.readlines() 
    f.close() 
    x=0 
    z = '' 
    l = [] 
    x = [] 
    i = 0 
    starting = '{:>4} {:>15} {:>15}'.format('Name', "Gender", "Year") 
    print(starting) 
    for p in line: 
     p = p.replace(',',' ') 
     x = p.index(' ') 
     name = p[0:x] 
     a = p.index('e 1') 
     gender = p[x:a+1] 
     year = p[(a+2):] 
     if len(name) == 3: 
      line_new = '{:>2} {:>15} {:>15}'.format(name, gender, year) 
     else: 
      line_new = '{:>5} {:>15} {:>15}'.format(name, gender, year) 
     print(line_new) 

的問題是,我想擁有的東西,如:

enter image description here 我希望把左邊的所有名稱(和我沒有問題),然後,在性別,我想都在同一垂直和同樣的事情,創造性別平等的清單年

+0

好吧,問自己一個問題 - 對齊文字意味着什麼?這怎麼能實現? – 2014-10-30 17:48:11

+0

你會得到什麼輸出?你的文件的內容是什麼樣的? – smac89 2014-10-30 17:48:54

+0

在這裏不那麼容易表達。我會嘗試將我的輸出 – pp94 2014-10-30 17:49:31

回答

0

未經檢驗的,但試試這個:

import itertools 
with open("data.txt") as data: 
    pep = [line.strip().split(',') for line in data] 
    widths = [len(max(r, key=len)) for r in itertools.izip_longest(*pep, fillvalue="")] 

    print "%-{0}%s%-{1}%s%-{2}%s".format(widths[0], widths[1], widths[2])\ 
    %("Name", "Gender", "Year") 

    print "\n".join(["%-{0}%s%-{1}%s%-{2}%s".format(widths[0], widths[1], widths[2])\ 
    %(attr[0], attr[1], attr[2]) for attr in pep])