简体   繁体   中英

Fixing right alignment of string formatting

I'm trying to align the output of the list like shown:

在此处输入图像描述

But it keeps coming out like this:

在此处输入图像描述

My code for all of this is:

subject_amount = int(input("\nHow many subject do you want to enrol? "))

class Subject:
def __init__(self, subject_code, credit_point):
    self.subject_code = subject_code
    self.credit_point = credit_point

subjects = []

for i in range(1, (subject_amount + 1)):
subject_code = input("\nEnter subject " + str(i) + ": ")
credit_point = int(input("Enter subject " + str(i) + " credit point: "))
subject = Subject(subject_code, credit_point)
subjects.append(subject)

print ("\nSelected subjects: ")

i, total = 0, 0

print("{0:<} {1:>11}".format("Subject: ", "CP"))

while(i < subject_amount):
print("{0:<} {1:14}".format(subjects[i].subject_code, subjects[i].credit_point))
total += subjects[i].credit_point
i = i + 1

print("{0:<} {1:>11}".format("Total cp: ", total))

I've tried changing the values for the spacing as well with no results.

Any feedback on the rest of my code is also greatly appreciated.

You can't do this using plain Python formatting because the amount of padding depends on both strings. Try defining a function such as:

def format_justified(left, right, total):
    padding = total - len(left)
    return "{{0}}{{1:>{}}}".format(padding).format(left, right)

then simply use:

print(format_justified("Total cp:", total, 25))

where 25 is the total line width you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM