cmckeeth
cmckeeth

Reputation: 95

How can I return a formatted list of tuples?

I have a list of tuples. I want to return them from an overridden str in a class. Can I format them so when the class is printed, they will appear stacked one tuple on top of another?

example code:

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)

the above code prints:

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

but I want it to print:

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

I won't always know how big the list of tuples will be, I am required to use overridden str for formatting. Is this possible and how could I do it?

Upvotes: 1

Views: 102

Answers (1)

akuiper
akuiper

Reputation: 214957

You can join the list of tuples with a new line character:

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

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

Upvotes: 6

Related Questions