【发布时间】:2017-08-10 08:46:19
【问题描述】:
我有一个工作函数,它接受由列表组成的列表并将其输出为表格。我只是缺少某些间距和新行。我对格式化字符串(和一般的python)很陌生。如何使用格式化函数来修复我的输出?
例如:
>>> show_table([['A','BB'],['C','DD']])
'| A | BB |\n| C | DD |\n'
>>> print(show_table([['A','BB'],['C','DD']]))
| A | BB |
| C | DD |
>>> show_table([['A','BBB','C'],['1','22','3333']])
'| A | BBB | C |\n| 1 | 22 | 3333 |\n'
>>> print(show_table([['A','BBB','C'],['1','22','3333']]))
| A | BBB | C |
| 1 | 22 | 3333 |
我实际输出的是什么:
>>>show_table([['A','BB'],['C','DD']])
'| A | BB | C | DD |\n'
>>>show_table([['A','BBB','C'],['1','22','3333']])
'| A | BBB | C | 1 | 22 | 3333 |\n'
>>>show_table([['A','BBB','C'],['1','22','3333']])
| A | BBB | C | 1 | 22 | 3333 |
我肯定需要使用格式化功能,但我不确定如何使用?
这是我当前的代码(我的缩进实际上是正确的,但我对 stackoverflow 格式感到很糟糕):
def show_table(table):
if table is None:
table=[]
new_table = ""
for row in table:
for val in row:
new_table += ("| " + val + " ")
new_table += "|\n"
return new_table
【问题讨论】:
-
@Zero 感谢编辑!~
-
在 SO 中进行代码格式化其实很容易;只需粘贴您的代码(使用 CTRL+C、CTRL+V 或其他),选择它,然后按 CTRL+K。
-
@ZeroPiraeus 我该如何格式化?
-
有点……参与 :-) 见下文……
标签: python-3.x matrix output string-formatting tabular