Python 如何返回元组的格式化列表?
我有一个元组列表。我想从类中重写的str返回它们。我是否可以格式化它们,以便在打印类时,它们将显示为一个元组叠在另一个元组上 示例代码:Python 如何返回元组的格式化列表?,python,formatting,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(
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进行格式化。这可能吗?我该怎么做?您可以使用新行字符加入元组列表:
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')
可以使用新行字符连接元组列表:
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')