【发布时间】:2020-12-17 16:10:17
【问题描述】:
基本上,我有一本字典,我想从中构造一个表。
字典的格式为:
dict={
'1':{'fruit':'apple',
'price':0.60,
'unit':'pieces',
'stock':60
},
'2':{'fruit':'cherries',
'price':15.49,
'unit':'kg',
'stock':5.6
},
and so on.
}
我希望表格看起来像数字正确对齐:
no |item | price | stock
----+----------+-------+----------
1 |apple | 0.60 | 60 pieces
----+----------+-------+----------
2 |cherries | 15.49 | 5.6 kg
and so on...
我确实不想打印这张表,我正在尝试编写一个函数,将 dict 作为输入,RETURNS 将此表作为字符串。
这是我的尝试:
def items(dct)
table="{0:<2} | {1:<33} | {2:^8} | {3:^11}".format("no", "item", "price","stock")
...
return table
我在格式化字符串时遇到了问题,我尝试添加换行符并尝试不同的东西,但我总是遇到各种错误,而且事情没有解决:( 我是Python新手,有人可以教育我吗? 谢谢!
【问题讨论】:
-
但我总是遇到各种错误,而且事情就是不正常向我们展示错误,并向我们展示你得到的输出。
标签: python string dictionary formatting