我无法让最后一行在显示中展开

0 投票
1 回答
34 浏览
提问于 2025-04-12 13:49

我有一段代码,用来根据输入打印一个日程表,但我无法让最后一行像标题那样展开。

我的showRecord代码如下...

Class Appointment:
    def __str__(appt):
        return f'{appt.date} {appt.start} {appt.end} {appt.description} {appt.venue} {appt.priority}'

其他代码直到

def showRecords(schedule):
    print('{:<15}{:<10}{:<8}{:<25}{:<25}{:<10}'.format("Date","Start","End","Subject","Venue","Priority")) # '<' here aligns text to left
    print('{:<15}{:<10}{:<8}{:<25}{:<25}{:<10}'.format("----","-----","---","-------","-----","--------"))
    for appointment in schedule:
        print(appointment)
    else:
        print("No more appointments found.")

我尝试了以下方法

print('{:<15}{:<10}{:<8}{:<25}{:<25}{:<10}'.format(schedule))

...还有...

print('{:<15}{:<10}{:<8}{:<13}{:<11}{:<10}'.format(date, start, end, description, venue, priority))

但是最后一行还是挤在一起,变成了这样...

在这里输入图片描述

我尝试了上面提到的几种代码,但都没能解决问题。请帮帮我。

注意:我已经添加了其余的代码!

1 个回答

1

你不能仅仅依赖于 __str__,因为它(这是正确的)在字符串格式化中没有任何填充或对齐的代码。

你也不能依赖于表头的填充和对齐,因为那只是针对表头的。

所以,如果你想让约会的文本表示有填充和对齐,你得自己动手。也就是说,你需要在要格式化和打印的字符串中添加填充和对齐的格式代码...

def showRecords(schedule):
    print('{:<15}{:<10}{:<8}{:<25}{:<25}{:<10}'.format("Date","Start","End","Subject","Venue","Priority")) # '<' here aligns text to left
    print('{:<15}{:<10}{:<8}{:<25}{:<25}{:<10}'.format("----","-----","---","-------","-----","--------"))
    for appt in schedule:
        print(f'{appt.date:<15}{appt.start:<10}{appt.end:<8}{appt.description:<25}{appt.venue:<25}{appt.priority:<10}')
    else:
        print("No more appointments found.")

撰写回答