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

的想法是首先创建包含所有数据,包括您的标题行的列表和传递给函数。然后计算每列中最宽的条目,并使用它为所有条目添加正确数量的间距。最后,在列之间添加额外的两个空格。