首页 > 解决方案 > 如何在 Python 中将输入更改为表单格式?

问题描述

我有这样的数据输入:

day_i = [“Bob: 1200”, “Alice: 2500”, “Celia: 110”, etc…]

我希望我的输出看起来像一个表格并计算数字的总和,如下所示:

Customer    Total purchase
Alice       100
Bob         120
Celia       110

标签: pythonformat

解决方案


假设day_i它是一个合适的 Python 字典,这就是我认为你所要求的。

day_i = {                                                                                                                                          
    'Bob': 1200, 
    'Alice': 2500, 
    'Celia': 110 
}

print("{:15s}{:15s}".format("Customer", "Total Purchase"))
for person in day_i:
    print("{:15s}{:<15d}".format(person, day_i[person]))

在使用此代码之前,我建议您在此处阅读有关 Python 的 string.Formatter 类的更多信息。


推荐阅读