user5361938
user5361938

Reputation:

String output formatting

My Code:

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^

Current output:

enter image description here

Desired output:

enter image description here

Would anyone know how to edit the area of interest in the commented piece of code to produce the desired output with the 9's lined up underneath the 3 in 13? Ive been trying .rjust(1) but it wont seem to work.

Upvotes: 1

Views: 75

Answers (1)

luoluo
luoluo

Reputation: 5533

Python string format support align.

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

'<' Forces the field to be left-aligned within the available space (this is the default for most objects).

'>' Forces the field to be right-aligned within the available space (this is the default for numbers).

'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.

'^' Forces the field to be centered within the available space.

So use {:>} for right align.

DEMO

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

In your case, just align the format in the following way:

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

Upvotes: 2

Related Questions