固定字符串格式的右对齐

问题描述 投票:0回答:1

我正在尝试对齐列表的输出,如图所示:

enter image description here

但是它一直这样冒出来:

enter image description here

我所有这些的代码是:

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

我也尝试过更改间距值,但没有结果。

对我的其余代码的任何反馈也将不胜感激。

python python-3.x string-formatting
1个回答
1
投票

您无法使用普通的Python格式执行此操作,因为填充量取决于两个字符串。尝试定义一个函数,例如:

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

然后只需使用:

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

其中25是所需的总线宽。

© www.soinside.com 2019 - 2024. All rights reserved.