【发布时间】:2021-12-06 17:07:21
【问题描述】:
有没有办法使用 PYTHON3
进行这种字符串格式化*************Food*************
initial deposit 1000.00
groceries -10.15
restaurant and more foo -15.89
Transfer to Clothing -50.00
数字右对齐,文本左对齐
ledger = [
{'amount':10000,'description': 'initial deposit'},
{'amount':-10.15,'description': 'groceries'},
{'amount':-15.89,'description': 'restaurant and more food costings'},
{'amount':-50,'description': 'Transfer to Clothing'}
]
请注意,描述键的值可能取决于用户... 所以它可能会更长,也可能不是这些
如果我这样做
string = ''
for dic in ledger:
string += '{description:<23}{amount:>7.2f}'.format(**dic)
string += '\n'
print(string)
输出是这样的……
initial deposit 10000.00
groceries -10.15
restaurant and more food costings -15.89
Transfer to Clothing -50.00
但我希望描述部分在数字之前停止
小数点也不对齐
所以我在这里还缺少什么 谢谢!!!!
【问题讨论】:
-
也许 f-string 有帮助。
-
是的!可以添加你的数据的python代码吗?
-
所有 Python 格式化方法都允许您指定字段是左对齐还是右对齐。阅读文档。