pip install tabulate

>>> from tabulate import tabulate

>>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6],
... ["Moon",1737,73.5],["Mars",3390,641.85]]
>>> print tabulate(table)
----- ------ -------------
Sun 696000 1.9891e+09
Earth 6371 5973.6
Moon 1737 73.5
Mars 3390 641.85
----- ------ -------------

The following tabular data types are supported:

* list of lists or another iterable of iterables
* list or another iterable of dicts (keys as columns)
* dict of iterables (keys as columns)
* two-dimensional NumPy array
* NumPy record arrays (names as columns)
* pandas.DataFrame

Examples in this file use Python2. Tabulate supports Python3 too.

Headers
~~~~~~~

The second optional argument named ``headers`` defines a list of
column headers to be used::

>>> print tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"])
Planet R (km) mass (x 10^29 kg)
-------- -------- -------------------
Sun 696000 1.9891e+09
Earth 6371 5973.6
Moon 1737 73.5
Mars 3390 641.85

If ``headers="firstrow"``, then the first row of data is used::

>>> print tabulate([["Name","Age"],["Alice",24],["Bob",19]],
... headers="firstrow")
Name Age
------ -----
Alice 24
Bob 19

If ``headers="keys"``, then the keys of a dictionary/dataframe, or
column indices are used. It also works for NumPy record arrays and
lists of dictionaries or named tuples::

>>> print tabulate({"Name": ["Alice", "Bob"],
... "Age": [24, 19]}, headers="keys")
Age Name
----- ------
24 Alice
19 Bob

Row Indices
~~~~~~~~~~~

By default, only pandas.DataFrame tables have an additional column
called row index. To add a similar column to any other type of table,
pass ``showindex="always"`` or ``showindex=True`` argument to
``tabulate()``. To suppress row indices for all types of data, pass
``showindex="never"`` or ``showindex=False``. To add a custom row
index column, pass ``showindex=rowIDs``, where ``rowIDs`` is some
iterable::

>>> print(tabulate([["F",24],["M",19]], showindex="always"))
- - --
0 F 24
1 M 19
- - --

Table format
~~~~~~~~~~~~

There is more than one way to format a table in plain text.
The third optional argument named ``tablefmt`` defines
how the table is formatted.

Supported table formats are:

- "plain"
- "simple"
- "grid"
- "fancy_grid"
- "pipe"
- "orgtbl"
- "jira"
- "presto"
- "psql"
- "rst"
- "mediawiki"
- "moinmoin"
- "youtrack"
- "html"
- "latex"
- "latex_raw"
- "latex_booktabs"
- "textile"

``plain`` tables do not use any pseudo-graphics to draw lines::

>>> table = [["spam",42],["eggs",451],["bacon",0]]
>>> headers = ["item", "qty"]
>>> print tabulate(table, headers, tablefmt="plain")
item qty
spam 42
eggs 451
bacon 0

``simple`` is the default format (the default may change in future
versions). It corresponds to ``simple_tables`` in `Pandoc Markdown
extensions`::

>>> print tabulate(table, headers, tablefmt="simple")
item qty
------ -----
spam 42
eggs 451
bacon 0

``grid`` is like tables formatted by Emacs' `table.el`
package. It corresponds to ``grid_tables`` in Pandoc Markdown
extensions::

>>> print tabulate(table, headers, tablefmt="grid")
+--------+-------+
| item | qty |
+========+=======+
| spam | 42 |
+--------+-------+
| eggs | 451 |
+--------+-------+
| bacon | 0 |
+--------+-------+

``fancy_grid`` draws a grid using box-drawing characters::

>>> print tabulate(table, headers, tablefmt="fancy_grid")
╒════════╤═══════╕
│ item │ qty │
╞════════╪═══════╡
│ spam │ 42 │
├────────┼───────┤
│ eggs │ 451 │
├────────┼───────┤
│ bacon │ 0 │
╘════════╧═══════╛

``presto`` is like tables formatted by Presto cli::

>>> print tabulate.tabulate()
item | qty
--------+-------
spam | 42
eggs | 451
bacon | 0

``psql`` is like tables formatted by Postgres' psql cli::

>>> print tabulate.tabulate()
+--------+-------+
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |
+--------+-------+

``pipe`` follows the conventions of `PHP Markdown Extra` extension. It
corresponds to ``pipe_tables`` in Pandoc. This format uses colons to
indicate column alignment::

>>> print tabulate(table, headers, tablefmt="pipe")
| item | qty |
|:-------|------:|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |

``orgtbl`` follows the conventions of Emacs `org-mode`, and is editable
also in the minor `orgtbl-mode`. Hence its name::

>>> print tabulate(table, headers, tablefmt="orgtbl")
| item | qty |
|--------+-------|
| spam | 42 |
| eggs | 451 |
| bacon | 0 |

``jira`` follows the conventions of Atlassian Jira markup language::

>>> print tabulate(table, headers, tablefmt="jira")
|| item || qty ||
| spam | 42 |
| eggs | 451 |
| bacon | 0 |

``rst`` formats data like a simple table of the `reStructuredText` format::

>>> print tabulate(table, headers, tablefmt="rst")
====== =====
item qty
====== =====
spam 42
eggs 451
bacon 0
====== =====

``mediawiki`` format produces a table markup used in `Wikipedia` and on
other MediaWiki-based sites::

>>> print tabulate(table, headers, tablefmt="mediawiki")
{| class="wikitable" style="text-align: left;"
|+ <!-- caption -->
|-
! item !! align="right"| qty
|-
| spam || align="right"| 42
|-
| eggs || align="right"| 451
|-
| bacon || align="right"| 0
|}

``moinmoin`` format produces a table markup used in `MoinMoin`
wikis::

>>> print tabulate(d,headers,tablefmt="moinmoin")
|| ''' item ''' || ''' quantity ''' ||
|| spam || 41.999 ||
|| eggs || 451 ||
|| bacon || ||

``youtrack`` format produces a table markup used in Youtrack
tickets::

>>> print tabulate(d,headers,tablefmt="youtrack")
|| item || quantity ||
| spam | 41.999 |
| eggs | 451 |
| bacon | |

``textile`` format produces a table markup used in `Textile` format::

>>> print tabulate(table, headers, tablefmt='textile')
|_. item |_. qty |
|<. spam |>. 42 |
|<. eggs |>. 451 |
|<. bacon |>. 0 |

``html`` produces standard HTML markup::

>>> print tabulate(table, headers, tablefmt="html")
<table>
<tbody>
<tr><th>item </th><th style="text-align: right;"> qty</th></tr>
<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`` format creates a ``tabular`` environment for LaTeX markup,
replacing special characters like ```` or ``\`` to their LaTeX
correspondents::

>>> print tabulate(table, headers, tablefmt="latex")
\begin{tabular}{lr}
\hline
item & qty \\
\hline
spam & 42 \\
eggs & 451 \\
bacon & 0 \\
\hline
\end{tabular}

``latex_raw`` behaves like ``latex`` but does not escape LaTeX commands
and special characters.

``latex_booktabs`` creates a ``tabular`` environment for LaTeX markup
using spacing and style from the ``booktabs`` package.

.. _Pandoc Markdown extensions: http://johnmacfarlane.net/pandoc/README.html#tables
.. _PHP Markdown Extra: http://michelf.ca/projects/php-markdown/extra/#table
.. _table.el: http://table.sourceforge.net/
.. _org-mode: http://orgmode.org/manual/Tables.html
.. _reStructuredText: http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables
.. _Textile: http://redcloth.org/hobix.com/textile/
.. _Wikipedia: http://www.mediawiki.org/wiki/Help:Tables
.. _MoinMoin: https://moinmo.in/

Column alignment
~~~~~~~~~~~~~~~~

``tabulate`` is smart about column alignment. It detects columns which
contain only numbers, and aligns them by a decimal point (or flushes
them to the right if they appear to be integers). Text columns are
flushed to the left.

You can override the default alignment with ``numalign`` and
``stralign`` named arguments. Possible column alignments are:
``right``, ``center``, ``left``, ``decimal`` (only for numbers), and
``None`` (to disable alignment).

Aligning by a decimal point works best when you need to compare
numbers at a glance::

>>> print tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]])
----------
1.2345
123.45
12.345
12345
1234.5
----------

Compare this with a more common right alignment::

>>> print tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]], numalign="right")
------
1.2345
123.45
12.345
12345
1234.5
------

For ``tabulate``, anything which can be parsed as a number is a
number. Even numbers represented as strings are aligned properly. This
feature comes in handy when reading a mixed table of text and numbers
from a file:

::

>>> import csv ; from StringIO import StringIO
>>> table = list(csv.reader(StringIO("spam, 42\neggs, 451\n")))
>>> table
[['spam', ' 42'], ['eggs', ' 451']]
>>> print tabulate(table)
---- ----
spam 42
eggs 451
---- ----

Number formatting
~~~~~~~~~~~~~~~~~

``tabulate`` allows to define custom number formatting applied to all
columns of decimal numbers. Use ``floatfmt`` named argument::

>>> print tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")
-- ------
pi 3.1416
e 2.7183
-- ------

``floatfmt`` argument can be a list or a tuple of format strings,
one per column, in which case every column may have different number formatting::

>>> print tabulate([[0.12345, 0.12345, 0.12345]], floatfmt=(".1f", ".3f"))
--- ----- -------
0.1 0.123 0.12345
--- ----- -------

Text formatting
~~~~~~~~~~~~~~~

By default, ``tabulate`` removes leading and trailing whitespace from text
columns. To disable whitespace removal, set the global module-level flag
``PRESERVE_WHITESPACE``::

import tabulate
tabulate.PRESERVE_WHITESPACE = True

Wide (fullwidth CJK) symbols
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

To properly align tables which contain wide characters (typically fullwidth
glyphs from Chinese, Japanese or Korean languages), the user should install
``wcwidth`` library. To install it together with ``tabulate``::

pip install tabulate[widechars]

Wide character support is enabled automatically if ``wcwidth`` library is
already installed. To disable wide characters support without uninstalling
``wcwidth``, set the global module-level flag ``WIDE_CHARS_MODE``::

import tabulate
tabulate.WIDE_CHARS_MODE = False

Multiline cells
~~~~~~~~~~~~~~~

Most table formats support multiline cell text (text containing newline
characters). The newline characters are honored as line break characters.

Multiline cells are supported for data rows and for header rows.

Further automatic line breaks are not inserted. Of course, some output formats
such as latex or html handle automatic formatting of the cell content on their
own, but for those that don't, the newline characters in the input cell text
are the only means to break a line in cell text.

Note that some output formats (e.g. simple, or plain) do not represent row
delimiters, so that the representation of multiline cells in such formats
may be ambiguous to the reader.

The following examples of formatted output use the following table with
a multiline cell, and headers with a multiline cell::

>>> table = [["eggs",451],["more\nspam",42]]
>>> headers = ["item\nname", "qty"]

``plain`` tables::

>>> print(tabulate(table, headers, tablefmt="plain"))
item qty
name
eggs 451
more 42
spam

``simple`` tables::

>>> print(tabulate(table, headers, tablefmt="simple"))
item qty
name
------ -----
eggs 451
more 42
spam

``grid`` tables::

>>> print(tabulate(table, headers, tablefmt="grid"))
+--------+-------+
| item | qty |
| name | |
+========+=======+
| eggs | 451 |
+--------+-------+
| more | 42 |
| spam | |
+--------+-------+

``fancy_grid`` tables::

>>> print(tabulate(table, headers, tablefmt="fancy_grid"))
╒════════╤═══════╕
│ item │ qty │
│ name │ │
╞════════╪═══════╡
│ eggs │ 451 │
├────────┼───────┤
│ more │ 42 │
│ spam │ │
╘════════╧═══════╛

``pipe`` tables::

>>> print(tabulate(table, headers, tablefmt="pipe"))
| item | qty |
| name | |
|:-------|------:|
| eggs | 451 |
| more | 42 |
| spam | |

``orgtbl`` tables::

>>> print(tabulate(table, headers, tablefmt="orgtbl"))
| item | qty |
| name | |
|--------+-------|
| eggs | 451 |
| more | 42 |
| spam | |

``jira`` tables::

>>> print(tabulate(table, headers, tablefmt="jira"))
| item | qty |
| name | |
|:-------|------:|
| eggs | 451 |
| more | 42 |
| spam | |

``presto`` tables::

>>> print(tabulate(table, headers, tablefmt="presto"))
item | qty
name |
--------+-------
eggs | 451
more | 42
spam |

``psql`` tables::

>>> print(tabulate(table, headers, tablefmt="psql"))
+--------+-------+
| item | qty |
| name | |
|--------+-------|
| eggs | 451 |
| more | 42 |
| spam | |
+--------+-------+

``rst`` tables::

>>> print(tabulate(table, headers, tablefmt="rst"))
====== =====
item qty
name
====== =====
eggs 451
more 42
spam
====== =====

Multiline cells are not well supported for the other table formats.

Usage of the command line utility
---------------------------------

::

Usage: tabulate [options] [FILE ...]

FILE a filename of the file with tabular data;
if "-" or missing, read data from stdin.

Options:

-h, --help show this message
-1, --header use the first row of data as a table header
-o FILE, --output FILE print table to FILE (default: stdout)
-s REGEXP, --sep REGEXP use a custom column separator (default: whitespace)
-F FPFMT, --float FPFMT floating point number format (default: g)
-f FMT, --format FMT set output table format; supported formats:
plain, simple, grid, fancy_grid, pipe, orgtbl,
rst, mediawiki, html, latex, latex_raw,
latex_booktabs, tsv
(default: simple)

Python -- tabulate 模块,的更多相关文章

  1. Python标准模块--threading

    1 模块简介 threading模块在Python1.5.2中首次引入,是低级thread模块的一个增强版.threading模块让线程使用起来更加容易,允许程序同一时间运行多个操作. 不过请注意,P ...

  2. Python的模块引用和查找路径

    模块间相互独立相互引用是任何一种编程语言的基础能力.对于“模块”这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译型的语言,比如C#中 ...

  3. Python Logging模块的简单使用

    前言 日志是非常重要的,最近有接触到这个,所以系统的看一下Python这个模块的用法.本文即为Logging模块的用法简介,主要参考文章为Python官方文档,链接见参考列表. 另外,Python的H ...

  4. Python标准模块--logging

    1 logging模块简介 logging模块是Python内置的标准模块,主要用于输出运行日志,可以设置输出日志的等级.日志保存路径.日志文件回滚等:相比print,具备如下优点: 可以通过设置不同 ...

  5. python基础-模块

    一.模块介绍                                                                                              ...

  6. python 安装模块

    python安装模块的方法很多,在此仅介绍一种,不需要安装其他附带的pip等,python安装完之后,配置环境变量,我由于中英文分号原因,环境变量始终没能配置成功汗. 1:下载模块的压缩文件解压到任意 ...

  7. python Queue模块

    先看一个很简单的例子 #coding:utf8 import Queue #queue是队列的意思 q=Queue.Queue(maxsize=10) #创建一个queue对象 for i in ra ...

  8. python logging模块可能会令人困惑的地方

    python logging模块主要是python提供的通用日志系统,使用的方法其实挺简单的,这块就不多介绍.下面主要会讲到在使用python logging模块的时候,涉及到多个python文件的调 ...

  9. Python引用模块和查找模块路径

    模块间相互独立相互引用是任何一种编程语言的基础能力.对于"模块"这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义.对于编译 ...

随机推荐

  1. node.js中使用zlib模块进行数据压缩和解压

    我们可以使用 zlib 模块来对数据进行压缩和解压处理,减小数据体积,加快传输速度. 一.通过创建转换流,对文件进行压缩和解压 const fs = require('fs'); const zlib ...

  2. zeromq学习记录(五)vc下多线程

    /************************************************************** 技术博客 http://www.cnblogs.com/itdef/   ...

  3. KD-树(下)

    来自于https://zhuanlan.zhihu.com/p/23966698 构造 kd 树的例子 上面抽象的定义和算法确实是很不好理解,举一个例子会清楚很多.首先随机在 中随机生成 13 个点作 ...

  4. strftime使用%F格式化日期失败

    报错:invalid format directive 解决:把%F换成%Y-%m-%d

  5. Git使用方法(精心整理,绝对够用)转载

    Git使用方法(精心整理,绝对够用)   一.git客户端(本地仓库)的一些操作 1.设置账户(需要和github账户设置一致) git config --global user.name xxx g ...

  6. Java从无知到入门书籍推荐

    0 前言 本文主题为Java Web书籍推荐 1 零基础学习 此处的零基础,指的是不懂或只懂if-else之类基本代码流程.初次接触,建议淘宝买一套**培训机构录播课程,看入门段视频.一是学习之初培养 ...

  7. Coding能力提升小技巧

    一.使用变量的一般原则 1.变量初始化原则: 通常在变量声明时初始化; 在靠近变量第一次使用的位置初始化; 在类的构造函数里初始化变量. 2.作用域: 使变量引用局部化,即把引用到变量的地方尽可能集中 ...

  8. day14_雷神_前端02

    # 前端day02 1. html标签 1. span标签设置宽高 设置宽高后,字体不会发生变化. 2. 盒模型 padding是border里面的距离: margin 是border边框外头的了属于 ...

  9. WPF 通过线程使用ProcessBar

    WPF下使用进度条也是非常方便的,如果直接采用循环然后给ProcessBar赋值,理论上是没有问题的,不过这样会卡主主UI线程,我们看到的效果等全部都结束循环后才出现最后的值. 所以需要采用线程或者后 ...

  10. Jmeter 结构、原理介绍 Jmeter结构、原理介绍(1)

    一.Jmeter 简介 1.是基于java语言的开源的应用软件. 2.可以进行接口测试.性能测试.接口及性能的自动化测试. 二.Jmeter体系结构 元件:可以理解为每一个菜单.如THHP请求.响应断 ...