Python - Print list of CSV strings in aligned columns(Python - 在对齐的列中打印 CSV 字符串列表)
问题描述
我编写了一个完全兼容 Python 2 和 Python 3 的代码片段.我编写的片段解析数据并将输出构建为 CSV 字符串列表.
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.
脚本提供了一个选项来:
- 将数据写入
CSV 文件,或 - 将其显示到
stdout.
虽然在显示到 stdout(第二个项目符号选项)时,我可以轻松地遍历列表并将 , 替换为 ,但这些项目长度是任意的,因此由于制表符的差异,请不要以很好的格式排列.
While I could easily iterate through the list and replace , with 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.
这是一个例子:
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)))
输出:
value1 | somevalue2 | value3 | reallylongvalue4 | value5 | superlongvalue6
value1 | value2 | reallylongvalue3 | value4 | value5 | somevalue6
这篇关于Python - 在对齐的列中打印 CSV 字符串列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 在对齐的列中打印 CSV 字符串列表
基础教程推荐
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
