2017-02-10 57 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