python格式问题,试图打印但出现sh

2024-03-29 05:41:57 发布

您现在位置:Python中文网/ 问答频道 /正文

enter image description here

我的代码:

        print(count,"\t",monthlyPayment,"\t",interest,"\t",loanAmount)

怎样才能使这个更整洁我不知道他们为什么不对齐?请指路?想用表格的形式吗


Tags: 代码count形式表格printinterestloanamountmonthlypayment
2条回答

使用format()。例如:

print('{:7d} {:10d} {:15.2f} {:15.2f}'.format(count, monthlyPayment, interest, loanAmount))

这里d代表十进制整数,f代表浮点数。数字就是宽度。{cd3>七位整数^表示宽度:

^{pr2}$

15.2f一个总宽度为15和2位小数的浮点数:

         1000.00

输出示例:

print('{:7d} {:10d} {:15.2f} {:15.2f}'.format(1, 300, 416.67, 99915.67))

是:

      1        300          416.67        99915.67

按制表符格式化在历史上是很棘手的。一旦某个字段的长度超过tabstep,整个格式就会中断。在本例中,该字段是头"payment"。在

不使用制表符,您可以计算列宽(以字符为单位)并创建匹配的str.format格式。我假设你有类似的数据

data = [(1, 500, 416.67, 99916.67),
        (2, 500, 416.32, 99832.99),
        ...]
header = [("month", "payment", "interest", "balance")]

正在打印:

^{pr2}$

相反,您将需要额外的时间运行数据。一次确定列宽,然后打印一次。在

colwidths = []
for column in zip(*(header + data)):
    colwidths.append(len(str(max, column, key=lambda s: len(str(s)))) + 1)
    # the `+ 1` in this case being the column margin

formatting = "".join(r"{{:{}}}".format(width for width in colwidths))

for line in header + data:
    print(formatting.format(*line))

或者,您可以让tabulate为您做这项工作。这是保存在pypi包管理器here中的第三方模块。安装时

pip install tabulate

然后使用如下代码:

import tabulate

data = [(1, 500, 416.67, 99916.67),
        (2, 500, 416.32, 99832.99),
        ...]
header = [("month", "payment", "interest", "balance")]

print(tabulate.tabulate(data, headers=*header))

相关问题 更多 >