在Python中用tabulate打印表单

tabulate是一个帮助你打印标准化表单的库,使用起来非常便捷,支持的格式较多。通过pip install tabulate安装之后即可使用,以下是一个简单的例子:

from tabulate import tabulate

table = [["spam", 42], ["eggs", 451], ["bacon", 0]]
headers = ["item", "qty"]

fmts = ["plain",
        "simple",
        "grid",
        "fancy_grid",
        "pipe",
        "orgtbl",
        "jira",
        "psql",
        "rst",
        "mediawiki",
        "moinmoin",
        "html",
        "latex",
        "latex_booktabs",
        "textile"]

for fmt in fmts:
    print fmt + ':'
    print tabulate(table, headers, tablefmt=fmt)

打印的表单如下:

plain:

item      qty
spam       42
eggs      451
bacon       0

simple:

item      qty
------  -----
spam       42
eggs      451
bacon       0

grid:

+--------+-------+
| item   |   qty |
+========+=======+
| spam   |    42 |
+--------+-------+
| eggs   |   451 |
+--------+-------+
| bacon  |     0 |
+--------+-------+

fancy_grid:

╒════════╤═══════╕
│ item   │   qty │
╞════════╪═══════╡
│ spam   │    42 │
├────────┼───────┤
│ eggs   │   451 │
├────────┼───────┤
│ bacon  │     0 │
╘════════╧═══════╛

pipe:

| item   |   qty |
|:-------|------:|
| spam   |    42 |
| eggs   |   451 |
| bacon  |     0 |

orgtbl:

| item   |   qty |
|--------+-------|
| spam   |    42 |
| eggs   |   451 |
| bacon  |     0 |

jira:

|| item   ||   qty ||
| spam   |    42 |
| eggs   |   451 |
| bacon  |     0 |

psql:

+--------+-------+
| item   |   qty |
|--------+-------|
| spam   |    42 |
| eggs   |   451 |
| bacon  |     0 |
+--------+-------+

rst:

======  =====
item      qty
======  =====
spam       42
eggs      451
bacon       0
======  =====

mediawiki:

{| class="wikitable" style="text-align: left;"
|+ 
|-
! item   !! align="right"|   qty
|-
| spam   || align="right"|    42
|-
| eggs   || align="right"|   451
|-
| bacon  || align="right"|     0
|}

moinmoin:

|| ''' item   ''' ||<style="text-align: right;"> '''   qty ''' ||
||  spam    ||<style="text-align: right;">     42  ||
||  eggs    ||<style="text-align: right;">    451  ||
||  bacon   ||<style="text-align: right;">      0  ||

html:

<table>
<thead>
<tr><th>item  </th><th style="text-align: right;">  qty</th></tr>
</thead>
<tbody>
<tr><td>spam  </td><td style="text-align: right;">   42</td></tr>
<tr><td>eggs  </td><td style="text-align: right;">  451</td></tr>
<tr><td>bacon </td><td style="text-align: right;">    0</td></tr>
</tbody>
</table>

latex:

\begin{tabular}{lr}
\hline
 item   &   qty \\
\hline
 spam   &    42 \\
 eggs   &   451 \\
 bacon  &     0 \\
\hline
\end{tabular}

latex_booktabs:

\begin{tabular}{lr}
\toprule
 item   &   qty \\
\midrule
 spam   &    42 \\
 eggs   &   451 \\
 bacon  &     0 \\
\bottomrule
\end{tabular}

textile:

|_.  item   |_.   qty |
|<. spam    |>.    42 |
|<. eggs    |>.   451 |
|<. bacon   |>.     0 |

在手机上阅读或分享本文请扫描以下二维码:
By @Zhengyi Yang in
Tags : #python, #table,

Comments

评论功能已关闭。