代码无法以正确的格式打印

时间:2017-02-10 02:00:34

标签: python

let tempDirString = tempDir.path

您好需要帮助那些知道如何正确使用.format的人,出于某种原因打印答案时。我希望如此。

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)

但我得到的显示输出是

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

21显示在错误的地方。我做错了什么?

2 个答案:

答案 0 :(得分:1)

在'Mathes Lost'字段后面似乎有一个'\ n'。你刚刚将输出粘贴在这里吗?如果是这样,您可能需要向我们展示原始输入文件的内容以提供更多信息:)

答案 1 :(得分: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

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