python中print的对齐,Python - 以对齐的列打印CSV字符串列表

这篇博客介绍了一个Python代码片段,该片段能够兼容Python2和Python3,用于解析数据并生成CSV字符串列表。提供了将数据写入CSV文件或显示到stdout的选项。为了解决stdout输出时因字段长度不一导致的对齐问题,作者使用了字符串格式化选项。通过计算每列的最大长度,然后使用`ljust`方法使每个单元格的宽度一致,实现了整齐的列对齐。示例代码展示了如何实现这个功能。
摘要由CSDN通过智能技术生成

I have written a fragment of code that is fully compatible with both Python 2 and Python 3. The fragment that I wrote parses data and it builds the output as a list of CSV strings.

The script provides an option to:

write the data to a CSV file, or

display it to the stdout.

While I could easily iterate through the list and replace , with \t when displaying to stdout (second bullet option), the items are of arbitrary length, so don't line up in a nice format due to variances in tabs.

I have done quite a bit of research, and I believe that string format options could accomplish what I'm after. That said, I can't seem to find an example that helps me get the syntax correct.

I would prefer to not use an external library. I am aware that there are many options available if I went that route, but I want the script to be as compatible and simple as possible.

Here is an example:

value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6

value1,value2,reallylongvalue3,value4,value5,somevalue6

Can you help me please? Any suggestion will be much appreciated.

解决方案import csv

from StringIO import StringIO

rows = list(csv.reader(StringIO(

'''value1,somevalue2,value3,reallylongvalue4,value5,superlongvalue6

value1,value2,reallylongvalue3,value4,value5,somevalue6''')))

widths = [max(len(row[i]) for row in rows) for i in range(len(rows[0]))]

for row in rows:

print(' | '.join(cell.ljust(width) for cell, width in zip(row, widths)))

Output:

value1 | somevalue2 | value3 | reallylongvalue4 | value5 | superlongvalue6

value1 | value2 | reallylongvalue3 | value4 | value5 | somevalue6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值