字符串输出格式

时间:2015-10-12 03:11:17

标签: python string

我的代码:

infile = open("table1.txt", "r")
a_list = infile.read().split("\n")
infile.close()

for pass_num in range(len(a_list)-1, 0, -1):

    for i in range(0, pass_num):

        if int(a_list[i].split(",")[1].strip()) > int(a_list[i+1].split(",")[1].strip()):
        a_list[i], a_list[i+1] = a_list[i+1], a_list[i]


        if (int(a_list[i].split(",")[1].strip()) == int(a_list[i+1].split(",")[1].strip())) and ((int(a_list[i].split(",")[2]) - int(a_list[i].split(",")[3].strip())) > (int(a_list[i+1].split(",")[2].strip()) - int(a_list[i+1].split(",")[3].strip()))):
        a_list[i], a_list[i+1] = a_list[i+1], a_list[i]


        if (int(a_list[i].split(",")[1].strip()) == int(a_list[i+1].split(",")[1].strip())) and ((int(a_list[i].split(",")[2]) - int(a_list[i].split(",")[3].strip())) == (int(a_list[i+1].split(",")[2].strip()) - int(a_list[i+1].split(",")[3].strip()))):
            if (int(a_list[i].split(",")[2])) > int(a_list[i+1].split(",")[2]):
                a_list[i], a_list[i+1] = a_list[i+1], a_list[i]

a_list.reverse()

print("    Team" + " "*(30-len("    Team")) + "Points" + " "*2 + "Diff" + " "*4 + "Goals")

for i in range(len(a_list)):

    team = a_list[i].split(",")[0]
    points = a_list[i].split(",")[1]
    goalfor = int(a_list[i].split(",")[2].strip())
    goalagainst = int(a_list[i].split(",")[3].strip())
    diff = goalfor - goalagainst

print(str(i+1).rjust(2) + ". " + '{0:27} {1:4} {2:4} {3:5} : {4:2}'.format(team, points, diff, goalfor, goalagainst)) 
#Area of interest above^

当前输出:

enter image description here

期望的输出:

enter image description here

是否有人知道如何在注释的代码段中编辑感兴趣的区域以使用9's lined up underneath the 3 in 13? Ive been trying .rjust(1)生成所需的输出,但它似乎无法正常工作。

1 个答案:

答案 0 :(得分:2)

Python字符串格式支持align

  

align :: ="<" | ">" | " =" | " ^"

     

'<'强制字段在可用空间内左对齐(这是大多数对象的默认值)。

     

'>'强制字段在可用空间内右对齐(这是数字的默认值)。

     

' ='强制将填充放置在符号(如果有)之后但在数字之前。这用于以“+000000120”形式打印字段。此对齐选项仅对数字类型有效。

     

' ^'强制字段在可用空间内居中。

因此请使用{:>}进行右对齐。

<强>样本

>>> print "{}\t{:<2}".format(1, 20) 
1   20
>>> print "{}\t{:<2}".format(1, 2)
1   2 
>>> print "{}\t{:>2}".format(1, 2)
1    2
>>> print "{}\t{:>2}".format(1, 20)
1   20

在您的情况下,只需按以下方式对齐格式:

print(str(1).rjust(2) + ". " + '{0:27} {1:>4} {2:4} {3:5} : {4:2}'.format("adasd", 1, -12, 1, 2))
                                        ^^^
相关问题