代码不打印.format编码

时间:2017-02-10 06:19:36

标签: python

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显示在错误的地方。我做错了什么?

2 个答案:

答案 0 :(得分:0)

默认情况下,整数与右对齐,字符串向左对齐:

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

您可以明确指定左对齐或将int转换为字符串,然后再将其传递给format

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))

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