2017-02-10 74 views
1
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,出於某種原因,當打印答案時。我會期待這一點。代碼未打印到.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被顯示在錯誤的地方。我做錯了什麼?

+0

看起來像'item [3]'包含換行符。你能檢查文件中的數據嗎? –

回答

0

另一種方式簡單地使用strip()刪除空格,

result = '{0:20} {1:20} {2:20} {3:20} {4:20}'.format(item[0], item[1], item[2], item[3],str(points).strip()) 

如果有新行可以省略,

str(points).replace('\n','') 
+0

部分正確的新行是在項目[3]沒有點,但謝謝 –

0

默認整數靠右側和字符串到左:

>>> '{:20}'.format(100) 
'     100' 
>>> '{:20}'.format('100') 
'100     ' 

你可以明確指定左對齊或轉給format之前轉換int爲字符串:

result = '{0:20} {1:20} {2:20} {3:20} {4:<20}'.format(item[0], item[1], item[2], item[3], points) 
result = '{0:20} {1:20} {2:20} {3:20} {4:20}'.format(item[0], item[1], item[2], item[3], str(points)) 
+0

不幸的是,它並沒有幫助它仍然打印一個類似的輸出,只有更接近的數字 –

+0

@MineFlamerKaiBin可以是建議的評論換行符,添加'print(item)'以查看內容是什麼。 – niemmi