python对齐输出

先说一下python中的.format格式化输出
在这里插入图片描述
python2.6开始,可以使用str.format进行轻松的格式化,

如上可以看到,对变量的处理简洁灵活,此外对数字的各种位数处理也很到位

{:<x}的语法表示左对齐(>为右对齐,^为居中),少于x位自动补齐(默认为空格补齐)

这里值得注意的是,x也可以作为变量代入:
在这里插入图片描述

示例:

data_filename = 'label.txt'
headers = 'picName', 'x1', 'y1','x2','y2','ClassName'  # Column names.

# Read the data from file into a list-of-lists table.
with open(data_filename) as file:
    datatable = [line.split() for line in file.read().splitlines()]
    

# Find the longest data value or header to be printed in each column.
widths = [max(len(value) for value in col)
            for col in zip(*(datatable + [headers]))]


# Print heading followed by the data in datatable.
# (Uses '>' to right-justify the data in some columns.)


format_spec = '{:{widths[0]}}  {:>{widths[1]}}  {:>{widths[2]}}'
print(format_spec.format(*headers, widths=widths))
for fields in datatable:
    print(format_spec.format(*fields, widths=widths))

参考网址:
python对齐输出
关于python:将文本文件转换为表格格式

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值