問題描述
我編寫了一個完全兼容 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 字符串列表的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!