2017-02-10 65 views
0
myfile = open('Results.txt') 
title = '{0:20} {1:20} {2:20} {3:20} {4:20}'.format('Player Nickname','Matches Played','Matches Won','Matches Lost','Points') 
print(title) 
for line in myfile: 
    item = line.split(',') 
    points = int(item[2]) * 3 
    if points != 0: 
     result = '{0:20} {1:20} {2:20} {3:20} {4:20}'.format(item[0], item[1], item[2], item[3],points) 
     print(result) 

嗨,那裏只是需要一些幫助,那些知道如何正確使用.format,出於某種原因,當打印答案時。我會期待這一點。代碼不以正確的格式打印

Player Nickname  Matches Played  Matches Won   Matches Lost   Points 
Leeroy    19     7     12     21 

但顯示的輸出我得到的是這種

Player Nickname  Matches Played  Matches Won   Matches Lost   Points    
Leeroy    19     7     12 
            21 

21被顯示在錯誤的地方。我做錯了什麼?

回答

1

看起來在'Mathes Lost'後面有一個'\ n'12.你剛剛在這裏粘貼了輸出嗎?如果是這樣,您可能需要向我們顯示原始輸入文件的內容,以提供更多信息:)

+0

沒有我寫了出來 繼承人的輸出 '玩家暱稱比賽場次比賽贏得比賽失分 Leeroy 19 7 12 21' –

0

與其試圖猜測每列的最佳間隔量,您可以編寫一個小函數(稱爲write_cols())計算每一列中的最寬的條目,然後自動空間東西相應:

def write_cols(data): 
    col_spacer = " "  # added between columns 
    widths = [0] * len(data[0]) 

    for row in data: 
     widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)] 

    return [col_spacer.join("{:<{width}}".format(col, width=widths[index]) for index, col in enumerate(row)) for row in data] 


data = [['Player Nickname', 'Matches Played', 'Matches Won', 'Matches Lost', 'Points']] 

with open('Results.txt') as myfile: 
    for line in myfile: 
     items = line.strip().split(',') 
     points = int(items[2]) * 3 

     if points != 0: 
      data.append([items[0], items[1], items[2], items[3], points]) 

    for line in write_cols(data): 
     print(line) 

這將顯示:

Player Nickname Matches Played Matches Won Matches Lost Points 
Leeroy   19    7    12    21 

的想法是首先創建包含所有數據,包括您的標題行的列表和傳遞給函數。然後計算每列中最寬的條目,並使用它爲所有條目添加正確數量的間距。最後,在列之間添加額外的兩個空格。