修复字符串格式的右对齐 [英] Fixing right alignment of string formatting

查看:31
本文介绍了修复字符串格式的右对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但它总是这样出现:

我的代码是:

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.

推荐答案

您不能使用纯 Python 格式来执行此操作,因为填充量取决于两个字符串.尝试定义一个函数,例如:

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)

然后简单地使用:

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

其中 25 是您想要的总线宽.

where 25 is the total line width you want.

这篇关于修复字符串格式的右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆