我有一个元组列表.我想从类中重写的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)
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
here are my tuples:
[('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
Run Code Online (Sandbox Code Playgroud)
但我希望它打印:
('a', 'b')
('c', 'd')
('e', 'f')
('g', 'h')
Run Code Online (Sandbox Code Playgroud)
我不会总是知道元组列表有多大,我需要使用重写的str进行格式化.这可能吗?我怎么能这样做?
您可以使用换行符加入元组列表:
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')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |