如何返回格式化的元组列表?

时间:2017-03-28 17:21:05

标签: python formatting

我有一个元组列表。我想从类中重写的 str 返回它们。我可以格式化它们,以便在打印课程时,它们会在另一个上面叠加一个元组吗?

示例代码:

class bar:
    tuplist = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
    def __str__(self):
        return 'here are my tuples: ' + '\n' + str(self.tuplist)

foo = bar()
print(foo)

以上代码打印:

here are my tuples: 
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]

但我想要打印:

('a', 'b')
('c', 'd')
('e', 'f')
('g', 'h')

我不会总是知道元组列表有多大,我需要使用重写的 str 进行格式化。这有可能吗?我怎么能这样做?

1 个答案:

答案 0 :(得分:6)

您可以使用换行符加入元组列表:

class course
{
private:
    string id;
    short credit_hours;
    string description;

public:
    course();
    course * remove_course(course*, int);
    static course * add_course_slots(course*, int);
    int add_course(course*,int);
    string get_id();
    string get_description();
    void course_display(int);
    short get_credit_hours();
};