【发布时间】:2021-07-22 21:42:38
【问题描述】:
我有python函数:
def myFunction(inputList):
outputList = ['Path | Type | Size']
for item in inputList:
outputList.append(item + ' | ' + parseFileType(item) + ' | ' + parseFileSize(item))
return outputList
我从这个函数得到以下输出:
Path | Type | Size
/etc/acpi | directory | 16 Kb.
/etc/adduser.conf | ASCII text | 4,0 Kb.
/bin/df | ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=8b0d9cd8d2256a94b9ea7e2248b6d8721cff588d, stripped | 84 Kb.
如何为这个函数的文本输出设置自动宽度,因为它看起来像:
Path | Type | Size
/etc/acpi | directory | 16 Kb.
/etc/adduser.conf | ASCII text | 4,0 Kb.
...
【问题讨论】:
-
好吧,你必须这样做。您必须遍历列表一次以确定每列的宽度,然后再次遍历它,用空格填充每列以填充该宽度。如何处理非常长的行由您决定,例如您的第三个条目。
-
你好,蒂姆,谢谢你,也许在某个地方可以使用一些算法来标准化我的输出?
-
不,这种事情没有标准。只有你知道你想要输出的样子。有些人会打印 HTML 并让浏览器让它变得漂亮。
-
我认为我应该使用类似“columnar”模块的东西,但它需要 Python v. 3.7.x,但我应该使用 Python v. 2.x 或 v. 3.5.x 的代码。跨度>
-
那个包里只有两个源文件。删除类型注释并将
f"..."字符串转换为常规字符串格式不会花费您很长时间。
标签: python parsing text output