Fixing right alignment of string formatting

。_饼干妹妹 提交于 2021-02-17 06:42:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/61883145/fixing-right-alignment-of-string-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!