python:textsp中的colspan

时间:2013-11-21 04:16:28

标签: python freetexttable

table = Texttable()
table.set_deco(Texttable.HEADER | Texttable.VLINES | Texttable.HLINES | Texttable.BORDER)
table.add_rows([ ["Name", "Age", "Nickname"],
                     ["Xavier Huon", 32, "Xav'"],
                     ["Baptiste Clement", 1, "Baby"] ])
print table.draw()

结果:

enter image description here

我怎么能做到这一点?

enter image description here

1 个答案:

答案 0 :(得分:1)

texttable没有真正好的方法。例如,它似乎不理解主标题下可能有其他分组列表。

相反,您可以通过一些巧妙的格式化来实现这一目标:

>>> table = Texttable()
>>> table.set_deco(Texttable.HEADER | Texttable.VLINES | Texttable.HLINES | Texttable.BORDER)
>>> 
>>> table.add_rows([ ["Name\nfirst   |   last", "Age", "Nickname"],
...                      ["Xavier   |    Huon", 32, "Xav'"],
...                      ["Baptiste | Clement", 1, "Baby"] ])
>>> print table.draw()
+--------------------+-----+----------+
|        Name        | Age | Nickname |
|  first   |   last  |     |          |
+====================+=====+==========+
| Xavier   |    Huon | 32  | Xav'     |
+--------------------+-----+----------+
| Baptiste | Clement | 1   | Baby     |
+--------------------+-----+----------+

唯一的问题是,如果表格越长,名称越长,firstlast名称项就会对齐。然而,你可以做一些数学来确定最大的名字,然后使用字符串格式左右对齐它。我将把它作为练习留给读者(和apparently double poster)。