Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.

License

NotificationsYou must be signed in to change notification settings

astanin/python-tabulate

Repository files navigation

Pretty-print tabular data in Python, a library and a command-lineutility.

The main use cases of the library are:

  • printing small tables without hassle: just one function call,formatting is guided by the data itself
  • authoring tabular data for lightweight plain-text markup: multipleoutput formats suitable for further editing or transformation
  • readable presentation of mixed textual and numeric data: smartcolumn alignment, configurable number formatting, alignment by adecimal point

Installation

To install the Python library and the command line utility, run:

pip install tabulate

The command line utility will be installed astabulate tobin onLinux (e.g./usr/bin); or astabulate.exe toScripts in yourPython installation on Windows (e.g.C:\Python39\Scripts\tabulate.exe).

You may consider installing the library only for the current user:

pip install tabulate --user

In this case the command line utility will be installed to~/.local/bin/tabulate on Linux and to%APPDATA%\Python\Scripts\tabulate.exe on Windows.

To install just the library on Unix-like operating systems:

TABULATE_INSTALL=lib-only pip install tabulate

On Windows:

set TABULATE_INSTALL=lib-onlypip install tabulate

Build status

python-tabulate

Library usage

The module provides just one function,tabulate, which takes a list oflists or another tabular data type as the first argument, and outputs anicely formatted plain-text table:

>>>from tabulateimport tabulate>>> table= [["Sun",696000,1989100000],["Earth",6371,5973.6],...          ["Moon",1737,73.5],["Mars",3390,641.85]]>>>print(tabulate(table))-----  ------  -------------Sun    696000     1.9891e+09Earth    6371  5973.6Moon     1737    73.5Mars     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)
  • list of dataclasses (field names as columns)
  • two-dimensional NumPy array
  • NumPy record arrays (names as columns)
  • pandas.DataFrame

Tabulate is a Python3 library.

Headers

The second optional argument namedheaders defines a list of columnheaders 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+09Earth         6371        5973.6Moon          1737          73.5Mars          3390         641.85

Ifheaders="firstrow", then the first row of data is used:

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

Ifheaders="keys", then the keys of a dictionary/dataframe, or columnindices are used. It also works for NumPy record arrays and lists ofdictionaries or named tuples:

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

When data is a list of dictionaries, a dictionary can be passed asheadersto replace the keys with other column labels:

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

Row Indices

By default, only pandas.DataFrame tables have an additional columncalled row index. To add a similar column to any other type of table,passshowindex="always" orshowindex=True argument totabulate().To suppress row indices for all types of data, passshowindex="never"orshowindex=False. To add a custom row index column, passshowindex=rowIDs, whererowIDs is some iterable:

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

Table format

There is more than one way to format a table in plain text. The thirdoptional argument namedtablefmt defines how the table is formatted.

Supported table formats are:

  • "plain"
  • "simple"
  • "github"
  • "grid"
  • "simple_grid"
  • "rounded_grid"
  • "heavy_grid"
  • "mixed_grid"
  • "double_grid"
  • "fancy_grid"
  • "outline"
  • "simple_outline"
  • "rounded_outline"
  • "heavy_outline"
  • "mixed_outline"
  • "double_outline"
  • "fancy_outline"
  • "pipe"
  • "orgtbl"
  • "asciidoc"
  • "jira"
  • "presto"
  • "pretty"
  • "psql"
  • "rst"
  • "mediawiki"
  • "moinmoin"
  • "youtrack"
  • "html"
  • "unsafehtml"
  • "latex"
  • "latex_raw"
  • "latex_booktabs"
  • "latex_longtable"
  • "textile"
  • "tsv"

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      qtyspam       42eggs      451bacon       0

simple is the default format (the default may change in futureversions). It corresponds tosimple_tables inPandoc Markdownextensions:

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

github follows the conventions of GitHub flavored Markdown. Itcorresponds to thepipe format without alignment colons:

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

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

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

simple_grid draws a grid using single-line box-drawing characters:

>>> print(tabulate(table, headers, tablefmt="simple_grid"))┌────────┬───────┐│ item   │   qty │├────────┼───────┤│ spam   │    42 │├────────┼───────┤│ eggs   │   451 │├────────┼───────┤│ bacon  │     0 │└────────┴───────┘

rounded_grid draws a grid using single-line box-drawing characters with rounded corners:

>>> print(tabulate(table, headers, tablefmt="rounded_grid"))╭────────┬───────╮│ item   │   qty │├────────┼───────┤│ spam   │    42 │├────────┼───────┤│ eggs   │   451 │├────────┼───────┤│ bacon  │     0 │╰────────┴───────╯

heavy_grid draws a grid using bold (thick) single-line box-drawing characters:

>>> print(tabulate(table, headers, tablefmt="heavy_grid"))┏━━━━━━━━┳━━━━━━━┓┃ item   ┃   qty ┃┣━━━━━━━━╋━━━━━━━┫┃ spam   ┃    42 ┃┣━━━━━━━━╋━━━━━━━┫┃ eggs   ┃   451 ┃┣━━━━━━━━╋━━━━━━━┫┃ bacon  ┃     0 ┃┗━━━━━━━━┻━━━━━━━┛

mixed_grid draws a grid using a mix of light (thin) and heavy (thick) lines box-drawing characters:

>>> print(tabulate(table, headers, tablefmt="mixed_grid"))┍━━━━━━━━┯━━━━━━━┑│ item   │   qty │┝━━━━━━━━┿━━━━━━━┥│ spam   │    42 │├────────┼───────┤│ eggs   │   451 │├────────┼───────┤│ bacon  │     0 │┕━━━━━━━━┷━━━━━━━┙

double_grid draws a grid using double-line box-drawing characters:

>>> print(tabulate(table, headers, tablefmt="double_grid"))╔════════╦═══════╗║ item   ║   qty ║╠════════╬═══════╣║ spam   ║    42 ║╠════════╬═══════╣║ eggs   ║   451 ║╠════════╬═══════╣║ bacon  ║     0 ║╚════════╩═══════╝

fancy_grid draws a grid using a mix of single anddouble-line box-drawing characters:

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

colon_grid is similar togrid but uses colons only to definecolumnwise content alignment , without whitespace padding,similar the alignment specification of Pandocgrid_tables:

>>> print(tabulate([["spam", 41.9999], ["eggs", "451.0"]],...                ["strings", "numbers"], "colon_grid",...                colalign=["right", "left"]))+-----------+-----------+| strings   | numbers   |+==========:+:==========+| spam      | 41.9999   |+-----------+-----------+| eggs      | 451       |+-----------+-----------+

outline is the same as thegrid format but doesn't draw lines between rows:

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

simple_outline is the same as thesimple_grid format but doesn't draw lines between rows:

>>> print(tabulate(table, headers, tablefmt="simple_outline"))┌────────┬───────┐│ item   │   qty │├────────┼───────┤│ spam   │    42 ││ eggs   │   451 ││ bacon  │     0 │└────────┴───────┘

rounded_outline is the same as therounded_grid format but doesn't draw lines between rows:

>>> print(tabulate(table, headers, tablefmt="rounded_outline"))╭────────┬───────╮│ item   │   qty │├────────┼───────┤│ spam   │    42 ││ eggs   │   451 ││ bacon  │     0 │╰────────┴───────╯

heavy_outline is the same as theheavy_grid format but doesn't draw lines between rows:

>>> print(tabulate(table, headers, tablefmt="heavy_outline"))┏━━━━━━━━┳━━━━━━━┓┃ item   ┃   qty ┃┣━━━━━━━━╋━━━━━━━┫┃ spam   ┃    42 ┃┃ eggs   ┃   451 ┃┃ bacon  ┃     0 ┃┗━━━━━━━━┻━━━━━━━┛

mixed_outline is the same as themixed_grid format but doesn't draw lines between rows:

>>> print(tabulate(table, headers, tablefmt="mixed_outline"))┍━━━━━━━━┯━━━━━━━┑│ item   │   qty │┝━━━━━━━━┿━━━━━━━┥│ spam   │    42 ││ eggs   │   451 ││ bacon  │     0 │┕━━━━━━━━┷━━━━━━━┙

double_outline is the same as thedouble_grid format but doesn't draw lines between rows:

>>> print(tabulate(table, headers, tablefmt="double_outline"))╔════════╦═══════╗║ item   ║   qty ║╠════════╬═══════╣║ spam   ║    42 ║║ eggs   ║   451 ║║ bacon  ║     0 ║╚════════╩═══════╝

fancy_outline is the same as thefancy_grid format but doesn't draw lines between rows:

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

presto is like tables formatted by Presto cli:

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

pretty attempts to be close to the format emitted by the PrettyTableslibrary:

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

psql is like tables formatted by Postgres' psql cli:

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

pipe follows the conventions ofPHP MarkdownExtra extension.It corresponds topipe_tables in Pandoc. This format uses colons toindicate column alignment:

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

asciidoc formats data like a simple table of theAsciiDoctorformat:

>>>print(tabulate(table, headers,tablefmt="asciidoc"))[cols="8<,7>",options="header"]|====| item   |   qty | spam   |    42 | eggs   |   451 | bacon  |     0 |====

orgtbl follows the conventions of Emacsorg-mode, and is editable alsoin 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 thereStructuredTextformat:

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

mediawiki format produces a table markup used inWikipedia and on otherMediaWiki-based sites:

>>>print(tabulate(table, headers,tablefmt="mediawiki")){||+ <!-- caption -->|-! item   !!|   qty|-| spam   |||    42|-| eggs   |||   451|-| bacon  |||     0|}

moinmoin format produces a table markup used inMoinMoin wikis:

>>>print(tabulate(table, headers,tablefmt="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  ||

youtrack format produces a table markup used in Youtrack tickets:

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

textile format produces a table markup used inTextile format:

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

html produces standard HTML markup as an html.escape'd strwith a .repr_html method so that Jupyter Lab and Notebook display the HTMLand a .str property so that the raw HTML remains accessible.unsafehtml table format can be used if an unescaped HTML is required:

>>>print(tabulate(table, headers,tablefmt="html"))<table><thead><tr><th>item  </th><th>  qty</th></tr></thead><tbody><tr><td>spam  </td><td>   42</td></tr><tr><td>eggs  </td><td>  451</td></tr><tr><td>bacon </td><td>    0</td></tr></tbody></table>

latex format creates atabular environment for LaTeX markup,replacing special characters like_ or\ to their LaTeXcorrespondents:

>>>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 likelatex but does not escape LaTeX commands andspecial characters.

latex_booktabs creates atabular environment for LaTeX markup usingspacing and style from thebooktabs package.

latex_longtable creates a table that can stretch along multiple pages,using thelongtable package.

Column alignment

tabulate is smart about column alignment. It detects columns whichcontain only numbers, and aligns them by a decimal point (or flushesthem to the right if they appear to be integers). Text columns areflushed to the left.

You can override the default alignment withnumalign andstralignnamed arguments. Possible column alignments are:right,center,left,decimal (only for numbers), andNone (to disable alignment).

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

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

Compare this with a more common right alignment:

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

Fortabulate, anything which can be parsed as a number is a number.Even numbers represented as strings are aligned properly. This featurecomes in handy when reading a mixed table of text and numbers from afile:

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

To disable this feature usedisable_numparse=True.

>>>print(tabulate([["Ver1","18.0"], ["Ver2","19.2"]],tablefmt="simple",disable_numparse=True))----  ----Ver1  18.0Ver2  19.2----  ----

Custom column alignment

tabulate allows a custom column alignment to override the smart alignment described above.Usecolglobalalign to define a global setting. Possible alignments are:right,center,left,decimal (only for numbers).Furthermore, you can definecolalign for column-specific alignment as a list or a tuple. Possible values areglobal (keeps global setting),right,center,left,decimal (only for numbers),None (to disable alignment). Missing alignments are treated asglobal.

>>>print(tabulate([[1,2,3,4],[111,222,333,444]],colglobalalign='center',colalign= ('global','left','right')))---  ---  ---  --- 1   2      3   4111  222  333  444---  ---  ---  ---

Custom header alignment

Headers' alignment can be defined separately from columns'. Like for columns, you can use:

  • headersglobalalign to define a header-specific global alignment setting. Possible values areright,center,left,None (to follow column alignment),
  • headersalign list or tuple to further specify header-wise alignment. Possible values areglobal (keeps global setting),same (follow column alignment),right,center,left,None (to disable alignment). Missing alignments are treated asglobal.
>>>print(tabulate([[1,2,3,4,5,6],[111,222,333,444,555,666]],colglobalalign='center',colalign= ('left',),headers= ['h','e','a','d','e','r'],headersglobalalign='right',headersalign= ('same','same','left','global','center')))h     e   a      d   e     r---  ---  ---  ---  ---  ---1     2    3    4    5    6111  222  333  444  555  666

Number formatting

tabulate allows to define custom number formatting applied to allcolumns of decimal numbers. Usefloatfmt named argument:

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

floatfmt argument can be a list or a tuple of format strings, one percolumn, 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---  -----  -------

intfmt works similarly for integers

>>> print(tabulate([["a",1000],["b",90000]], intfmt=","))-  ------a   1,000b  90,000-  ------

Type Deduction and Missing Values

Whentabulate sees numerical data (with our without comma separators), itattempts to align the column on the decimal point. However, if it observesnon-numerical data in the column, it aligns it to the left by default. Ifdata is missing in a column (either None or empty values), the remainingdata in the column is used to infer the type:

>>>from fractionsimport Fraction>>> test_table= [...    [None,"1.23423515351", Fraction(1,3)],...    [Fraction(56789,1000000),12345.1,b"abc"],...    ["",b"",None],...    [Fraction(10000,3),None,""],... ]>>>print(tabulate(test_table,floatfmt=",.5g",missingval="?"))------------  -----------  ---    ?              1.2342  1/3    0.056789  12,345       abc                           ?3,333.3            ?------------  -----------  ---

The deduced type (eg. str, float) influences the rendering of any typesthat have alternative representations. For example, sinceFraction hasmethods__str__ and__float__ defined (and hence is convertible to afloat and also has astr representation), the appropriaterepresentation is selected for the column's deduced type. In order to notlose precision accidentally, types having both an__int__ and__float__ represention will be considered afloat.

Therefore, if your table contains types convertible to int/float but you'dprefer they be represented as strings, or your stringsmight all looklike numbers such as "1e23": either convert them to the desiredrepresentation before youtabulate, or ensure that the column alwayscontains at least one otherstr.

Text formatting

By default,tabulate removes leading and trailing whitespace from textcolumns. To disable whitespace removal, passpreserve_whitespace=True.Older versions of the library used a global module-level flag PRESERVE_WHITESPACE.

Wide (fullwidth CJK) symbols

To properly align tables which contain wide characters (typicallyfullwidth glyphs from Chinese, Japanese or Korean languages), the usershould installwcwidth library. To install it together withtabulate:

pip install tabulate[widechars]

Wide character support is enabled automatically ifwcwidth library isalready installed. To disable wide characters support withoutuninstallingwcwidth, set the global module-level flagWIDE_CHARS_MODE:

importtabulatetabulate.WIDE_CHARS_MODE=False

Multiline cells

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

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

Further automatic line breaks are not inserted. Of course, some outputformats such as latex or html handle automatic formatting of the cellcontent on their own, but for those that don't, the newline charactersin 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 representrow delimiters, so that the representation of multiline cells in suchformats may be ambiguous to the reader.

The following examples of formatted output use the following table witha 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      qtynameeggs      451more       42spam

simple tables:

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

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   |

pretty tables:

>>>print(tabulate(table, headers,tablefmt="pretty"))+------+-----+| 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      qtyname======  =====eggs      451more       42spam======  =====

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

Automating Multilines

While tabulate supports data passed in with multilines entries explicitly provided,it also provides some support to help manage this work internally.

Themaxcolwidths argument is a list where each entry specifies the max width forit's respective column. Any cell that will exceed this will automatically wrap the content.To assign the same max width for all columns, a singular int scaler can be used.

UseNone for any columns where an explicit maximum does not need to be provided,and thus no automate multiline wrapping will take place.

The wrapping uses the python standardtextwrap.wrapfunction with default parameters - aside from width.

This example demonstrates usage of automatic multiline wrapping, though typicallythe lines being wrapped would probably be significantly longer than this.

>>>print(tabulate([["John Smith","Middle Manager"]],headers=["Name","Title"],tablefmt="grid",maxcolwidths=[None,8]))+------------+---------+| Name       | Title   |+============+=========+| John Smith | Middle  ||            | Manager |+------------+---------+

Adding Separating lines

One might want to add one or more separating lines to highlight different sections in a table.

The separating lines will be of the same type as the one defined by the specified formatter as either thelinebetweenrows, linebelowheader, linebelow, lineabove or just a simple empty line when none is defined for the formatter

>>> from tabulate import tabulate, SEPARATING_LINEtable = [["Earth",6371],         ["Mars",3390],         SEPARATING_LINE,         ["Moon",1737]]print(tabulate(table, tablefmt="simple"))-----  ----Earth  6371Mars   3390-----  ----Moon   1737-----  ----

ANSI support

ANSI escape codes are non-printable byte sequences usually used for terminal operations like settingcolor output or modifying cursor positions. Because multi-byte ANSI sequences are inherently non-printable,they can still introduce unwanted extra length to strings. For example:

>>> len('\033[31mthis text is red\033[0m')  # printable length is 1625

To deal with this, string lengths are calculated after first removing all ANSI escape sequences. This ensuresthat the actual printable length is used for column widths, rather than the byte length. In the final, printabletable, however, ANSI escape sequences are not removed so the original styling is preserved.

Some terminals support a special grouping of ANSI escape sequences that are intended to display hyperlinksmuch in the same way they are shown in browsers. These are handled just as mentioned before: non-printableANSI escape sequences are removed prior to string length calculation. The only diifference with escapedhyperlinks is that column width will be based on the length of the URLtext rather than the URLitself (terminals would show this text). For example:

>>> len('\x1b]8;;https://example.com\x1b\\example\x1b]8;;\x1b\\')  # display length is 7, showing 'example'40

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)-I INTFMT, --int INTFMT   integer point number format (default: "")-f FMT, --format FMT      set output table format; supported formats:                          plain, simple, github, grid, fancy_grid, pipe,                          orgtbl, rst, mediawiki, html, latex, latex_raw,                          latex_booktabs, latex_longtable, tsv                          (default: simple)

Performance considerations

Such features as decimal point alignment and trying to parse everythingas a number imply thattabulate:

  • has to "guess" how to print a particular tabular data type
  • needs to keep the entire table in-memory
  • has to "transpose" the table twice
  • does much more work than it may appear

It may not be suitable for serializing really big tables (but who'sgoing to do that, anyway?) or printing tables in performance sensitiveapplications.tabulate is about two orders of magnitude slower thansimply joining lists of values with a tab, comma, or other separator.

At the same time,tabulate is comparable to other tablepretty-printers. Given a 10x10 table (a list of lists) of mixed text andnumeric data,tabulate appears to be faster thanPrettyTable andtexttable.The following mini-benchmark was run in Python 3.11.9 on Windows 11 (x64):

==================================  ==========  ===========Table formatter                       time, μs    rel. time==================================  ==========  ===========join with tabs and newlines                6.3          1.0csv to StringIO                            6.6          1.0tabulate (0.10.0)                        249.2         39.3tabulate (0.10.0, WIDE_CHARS_MODE)       325.6         51.4texttable (1.7.0)                        579.3         91.5PrettyTable (3.11.0)                     605.5         95.6==================================  ==========  ===========

Version history

The full version history can be found at thechangelog.

How to contribute

Contributions should include tests and an explanation for the changesthey propose. Documentation (examples, docstrings, README.md) should beupdated accordingly.

This project usespytest testingframework andtox to automate testing indifferent environments. Add tests to one of the files in thetest/folder.

To run tests on all supported Python versions, make sure all Pythoninterpreters,pytest andtox are installed, then runtox in the rootof the project source tree.

On Linuxtox expects to find executables likepython3.11,python3.12 etc.On Windows it looks forC:\Python311\python.exe,C:\Python312\python.exe etc. respectively.

One way to install all the required versions of the Python interpreter is to usepyenv.All versions can then be easily installed with something like:

 pyenv install 3.11.7 pyenv install 3.12.1 ...

Don't forget to change yourPATH so thattox knows how to find all the installed versions. Something like

 export PATH="${PATH}:${HOME}/.pyenv/shims"

To test only some Python environments, use-e option. For example, totest only against Python 3.11 and Python 3.12, run:

tox -e py311,py312

in the root of the project source tree.

To enable NumPy and Pandas tests, run:

tox -e py311-extra,py312-extra

(this may take a long time the first time, because NumPy and Pandas willhave to be installed in the new virtual environments)

To fix code formatting:

tox -e lint

Seetox.ini file to learn how to use to testindividual Python versions.

To test the "doctest" examples and their outputs inREADME.md:

python3 -m pip install pytest-doctestplus[md]python3 -m doctest README.md

Contributors

Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, BillRyder, Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg(anonymous), Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett,Amjith Ramanujam, Jan Schulz, Simon Percivall, Javier SantacruzLópez-Cepero, Sam Denton, Alexey Ziyangirov, acaird, Cesar Sanchez,naught101, John Vandenberg, Zack Dever, Christian Clauss, BenjaminMaier, Andy MacKinlay, Thomas Roten, Jue Wang, Joe King, Samuel Phan,Nick Satterly, Daniel Robbins, Dmitry B, Lars Butler, Andreas Maier,Dick Marinus, Sébastien Celles, Yago González, Andrew Gaul, Wim Glenn,Jean Michel Rouly, Tim Gates, John Vandenberg, Sorin Sbarnea,Wes Turner, Andrew Tija, Marco Gorelli, Sean McGinnis, danja100,endolith, Dominic Davis-Foster, pavlocat, Daniel Aslau, paulc,Felix Yan, Shane Loretz, Frank Busse, Harsh Singh, Derek Weitzel,Vladimir Vrzić, 서승우 (chrd5273), Georgy Frolov, Christian Cwienk,Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade,jamescooke, Matt Warner, Jérôme Provensal, Michał Górny, Kevin Deldycke,Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH,Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan,Dimitri Papadopoulos, Élie Goudout, Racerroar888, Phill Zarfos,Keyacom, Andrew Coffey, Arpit Jain, Israel Roldan, ilya112358,Dan Nicholson, Frederik Scheerer, cdar07 (cdar), Racerroar888,Perry Kundert.

About

Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp