Package: tabulate-expwidth
This Pypi package is made so that packages depending oon this fork ofpython-tabulatecan also go on Pypi. Or I getError: Can't have direct dependency: 'tabulate @ git+https://github.com.... Local changes in this fork has been raised athttps://github.com/astanin/python-tabulate/issues/174.python-tabulatePretty-print tabular data in Python, a library and a command-line
utility.The main use cases of the library are:printing small tables without hassle: just one function call,
formatting is guided by the data itselfauthoring tabular data for lightweight plain-text markup: multiple
output formats suitable for further editing or transformationreadable presentation of mixed textual and numeric data: smart
column alignment, configurable number formatting, alignment by a
decimal pointInstallationTo install the Python library and the command line utility, run:pipinstalltabulateThe command line utility will be installed astabulatetobinon
Linux (e.g./usr/bin); or astabulate.exetoScriptsin your
Python installation on Windows (e.g.C:\Python39\Scripts\tabulate.exe).You may consider installing the library only for the current user:pipinstalltabulate--userIn this case the command line utility will be installed to~/.local/bin/tabulateon Linux and to%APPDATA%\Python\Scripts\tabulate.exeon Windows.To install just the library on Unix-like operating systems:TABULATE_INSTALL=lib-onlypipinstalltabulateOn Windows:setTABULATE_INSTALL=lib-only
pipinstalltabulateThe module provides just one function,tabulate, which takes a list of
lists or another tabular data type as the first argument, and outputs a
nicely formatted plain-text table:>>>fromtabulateimporttabulate>>>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 iterableslist or another iterable of dicts (keys as columns)dict of iterables (keys as columns)list of dataclasses (Python 3.7+ only, field names as columns)two-dimensional NumPy arrayNumPy record arrays (names as columns)pandas.DataFrameExamples in this file use Python2. Tabulate supports Python3 too.HeadersThe second optional argument namedheadersdefines 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+09Earth         6371        5973.6Moon          1737          73.5Mars          3390         641.85Ifheaders="firstrow", then the first row of data is used:>>>print(tabulate([["Name","Age"],["Alice",24],["Bob",19]],...headers="firstrow"))Name      Age------  -----Alice      24Bob        19Ifheaders="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  Alice19  BobRow IndicesBy default, only pandas.DataFrame tables have an additional column
called row index. To add a similar column to any other type of table,
passshowindex="always"orshowindex=Trueargument totabulate().
To suppress row indices for all types of data, passshowindex="never"orshowindex=False. To add a custom row index column, passshowindex=rowIDs, whererowIDsis some iterable:>>>print(tabulate([["F",24],["M",19]],showindex="always"))-  -  --0  F  241  M  19-  -  --Table formatThere is more than one way to format a table in plain text. The third
optional argument namedtablefmtdefines how the table is formatted.Supported table formats are:"plain""simple""github""grid""simple_grid""rounded_grid""double_grid""fancy_grid""outline""simple_outline""rounded_outline""double_outline""fancy_outline""pipe""orgtbl""jira""presto""pretty""psql""rst""mediawiki""moinmoin""youtrack""html""unsafehtml""latex""latex_raw""latex_booktabs""latex_longtable""textile""tsv"plaintables 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       0simpleis the default format (the default may change in future
versions). It corresponds tosimple_tablesinPandoc Markdown
extensions:>>>print(tabulate(table,headers,tablefmt="simple"))item      qty------  -----spam       42eggs      451bacon       0githubfollows the conventions of GitHub flavored Markdown. It
corresponds to thepipeformat without alignment colons:>>>print(tabulate(table,headers,tablefmt="github"))| item   | qty   ||--------|-------|| spam   | 42    || eggs   | 451   || bacon  | 0     |gridis like tables formatted by Emacs'table.elpackage. It corresponds togrid_tablesin Pandoc Markdown extensions:>>>print(tabulate(table,headers,tablefmt="grid"))+--------+-------+| item   |   qty |+========+=======+| spam   |    42 |+--------+-------+| eggs   |   451 |+--------+-------+| bacon  |     0 |+--------+-------+simple_griddraws a grid using single-line box-drawing characters:>>> print(tabulate(table, headers, tablefmt="simple_grid"))
┌────────┬───────┐
│ item   │   qty │
├────────┼───────┤
│ spam   │    42 │
├────────┼───────┤
│ eggs   │   451 │
├────────┼───────┤
│ bacon  │     0 │
└────────┴───────┘rounded_griddraws 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 │
╰────────┴───────╯double_griddraws a grid using double-line box-drawing characters:>>> print(tabulate(table, headers, tablefmt="double_grid"))
╔════════╦═══════╗
║ item   ║   qty ║
╠════════╬═══════╣
║ spam   ║    42 ║
╠════════╬═══════╣
║ eggs   ║   451 ║
╠════════╬═══════╣
║ bacon  ║     0 ║
╚════════╩═══════╝fancy_griddraws a grid using a mix of single and
double-line box-drawing characters:>>>print(tabulate(table,headers,tablefmt="fancy_grid"))╒════════╤═══════╕│ item   │   qty │╞════════╪═══════╡│ spam   │    42 │├────────┼───────┤│ eggs   │   451 │├────────┼───────┤│ bacon  │     0 │╘════════╧═══════╛outlineis the same as thegridformat but doesn't draw lines between rows:>>> print(tabulate(table, headers, tablefmt="outline"))
+--------+-------+
| item   |   qty |
+========+=======+
| spam   |    42 |
| eggs   |   451 |
| bacon  |     0 |
+--------+-------+simple_outlineis the same as thesimple_gridformat but doesn't draw lines between rows:>>> print(tabulate(table, headers, tablefmt="simple_outline"))
┌────────┬───────┐
│ item   │   qty │
├────────┼───────┤
│ spam   │    42 │
│ eggs   │   451 │
│ bacon  │     0 │
└────────┴───────┘rounded_outlineis the same as therounded_gridformat but doesn't draw lines between rows:>>> print(tabulate(table, headers, tablefmt="rounded_outline"))
╭────────┬───────╮
│ item   │   qty │
├────────┼───────┤
│ spam   │    42 │
│ eggs   │   451 │
│ bacon  │     0 │
╰────────┴───────╯double_outlineis the same as thedouble_gridformat but doesn't draw lines between rows:>>> print(tabulate(table, headers, tablefmt="double_outline"))
╔════════╦═══════╗
║ item   ║   qty ║
╠════════╬═══════╣
║ spam   ║    42 ║
║ eggs   ║   451 ║
║ bacon  ║     0 ║
╚════════╩═══════╝fancy_outlineis the same as thefancy_gridformat but doesn't draw lines between rows:>>> print(tabulate(table, headers, tablefmt="fancy_outline"))
╒════════╤═══════╕
│ item   │   qty │
╞════════╪═══════╡
│ spam   │    42 │
│ eggs   │   451 │
│ bacon  │     0 │
╘════════╧═══════╛prestois like tables formatted by Presto cli:>>>print(tabulate(table,headers,tablefmt="presto"))item   |   qty--------+-------spam   |    42eggs   |   451bacon  |     0prettyattempts to be close to the format emitted by the PrettyTables
library:>>>print(tabulate(table,headers,tablefmt="pretty"))+-------+-----+| item  | qty |+-------+-----+| spam  | 42  || eggs  | 451 || bacon |  0  |+-------+-----+psqlis like tables formatted by Postgres' psql cli:>>>print(tabulate(table,headers,tablefmt="psql"))+--------+-------+| item   |   qty ||--------+-------|| spam   |    42 || eggs   |   451 || bacon  |     0 |+--------+-------+pipefollows the conventions ofPHP Markdown
Extraextension.
It corresponds topipe_tablesin Pandoc. This format uses colons to
indicate column alignment:>>>print(tabulate(table,headers,tablefmt="pipe"))| item   |   qty ||:-------|------:|| spam   |    42 || eggs   |   451 || bacon  |     0 |orgtblfollows the conventions of Emacsorg-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 |jirafollows the conventions of Atlassian Jira markup language:>>>print(tabulate(table,headers,tablefmt="jira"))|| item   ||   qty ||| spam   |    42 || eggs   |   451 || bacon  |     0 |rstformats data like a simple table of thereStructuredTextformat:>>>print(tabulate(table,headers,tablefmt="rst"))======  =====item      qty======  =====spam       42eggs      451bacon       0======  =====mediawikiformat produces a table markup used inWikipediaand 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|}moinmoinformat produces a table markup used inMoinMoinwikis:>>>print(tabulate(table,headers,tablefmt="moinmoin"))|| ''' item   ''' || ''' quantity   ''' ||||  spam    ||  41.999      ||||  eggs    ||  451         ||||  bacon   ||              ||youtrackformat produces a table markup used in Youtrack tickets:>>>print(tabulate(table,headers,tablefmt="youtrack"))||  item    ||  quantity   |||   spam    |  41.999      ||   eggs    |  451         ||   bacon   |              |textileformat produces a table markup used inTextileformat:>>>print(tabulate(table,headers,tablefmt="textile"))|_.  item   |_.   qty ||<. spam    |>.    42 ||<. eggs    |>.   451 ||<. bacon   |>.     0 |htmlproduces standard HTML markup as an html.escape'd str
with a .repr_htmlmethod so that Jupyter Lab and Notebook display the HTML
and a .str property so that the raw HTML remains accessible.unsafehtmltable format can be used if an unescaped HTML is required:>>>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>latexformat creates atabularenvironment for LaTeX markup,
replacing special characters like_or\to their LaTeX
correspondents:>>>print(tabulate(table,headers,tablefmt="latex"))\begin{tabular}{lr}\hlineitem   &   qty \\\hlinespam   &    42 \\eggs   &   451 \\bacon  &     0 \\\hline\end{tabular}latex_rawbehaves likelatexbut does not escape LaTeX commands and
special characters.latex_booktabscreates atabularenvironment for LaTeX markup using
spacing and style from thebooktabspackage.latex_longtablecreates a table that can stretch along multiple pages,
using thelongtablepackage.Column alignmenttabulateis 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 withnumalignandstralignnamed 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 numbers
at a glance:>>>print(tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]]))----------1.2345123.4512.345123451234.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.345123451234.5------Fortabulate, 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:>>>importcsv;fromStringIOimportStringIO>>>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.tabulate([["Ver1","18.0"],["Ver2","19.2"]],tablefmt="simple",disable_numparse=True))----  ----Ver1  18.0Ver2  19.2----  ----Custom column alignmenttabulateallows a custom column alignment to override the above. Thecolalignargument can be a list or a tuple ofstralignnamed
arguments. Possible column alignments are:right,center,left,decimal(only for numbers), andNone(to disable alignment).
Omitting an alignment uses the default. For example:>>>print(tabulate([["one","two"],["three","four"]],colalign=("right",))-----  ----one  twothree  four-----  ----Number formattingtabulateallows to define custom number formatting applied to all
columns of decimal numbers. Usefloatfmtnamed argument:>>>print(tabulate([["pi",3.141593],["e",2.718282]],floatfmt=".4f"))--  ------pi  3.1416e   2.7183--  ------floatfmtargument 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---  -----  -------intfmtworks similarly for integers>>> print(tabulate([["a",1000],["b",90000]], intfmt=","))
-  ------
a   1,000
b  90,000
-  ------Text formattingBy default,tabulateremoves leading and trailing whitespace from text
columns. To disable whitespace removal, set the global module-level flagPRESERVE_WHITESPACE:importtabulatetabulate.PRESERVE_WHITESPACE=TrueWide (fullwidth CJK) symbolsTo properly align tables which contain wide characters (typically
fullwidth glyphs from Chinese, Japanese or Korean languages), the user
should installwcwidthlibrary. To install it together withtabulate:pipinstalltabulate[widechars]Wide character support is enabled automatically ifwcwidthlibrary is
already installed. To disable wide characters support without
uninstallingwcwidth, set the global module-level flagWIDE_CHARS_MODE:importtabulatetabulate.WIDE_CHARS_MODE=FalseMultiline cellsMost 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"]plaintables:>>>print(tabulate(table,headers,tablefmt="plain"))item      qtynameeggs      451more       42spamsimpletables:>>>print(tabulate(table,headers,tablefmt="simple"))item      qtyname------  -----eggs      451more       42spamgridtables:>>>print(tabulate(table,headers,tablefmt="grid"))+--------+-------+| item   |   qty || name   |       |+========+=======+| eggs   |   451 |+--------+-------+| more   |    42 || spam   |       |+--------+-------+fancy_gridtables:>>>print(tabulate(table,headers,tablefmt="fancy_grid"))╒════════╤═══════╕│ item   │   qty ││ name   │       │╞════════╪═══════╡│ eggs   │   451 │├────────┼───────┤│ more   │    42 ││ spam   │       │╘════════╧═══════╛pipetables:>>>print(tabulate(table,headers,tablefmt="pipe"))| item   |   qty || name   |       ||:-------|------:|| eggs   |   451 || more   |    42 || spam   |       |orgtbltables:>>>print(tabulate(table,headers,tablefmt="orgtbl"))| item   |   qty || name   |       ||--------+-------|| eggs   |   451 || more   |    42 || spam   |       |jiratables:>>>print(tabulate(table,headers,tablefmt="jira"))| item   |   qty || name   |       ||:-------|------:|| eggs   |   451 || more   |    42 || spam   |       |prestotables:>>>print(tabulate(table,headers,tablefmt="presto"))item   |   qtyname   |--------+-------eggs   |   451more   |    42spam   |prettytables:>>>print(tabulate(table,headers,tablefmt="pretty"))+------+-----+| item | qty || name |     |+------+-----+| eggs | 451 || more | 42  || spam |     |+------+-----+psqltables:>>>print(tabulate(table,headers,tablefmt="psql"))+--------+-------+| item   |   qty || name   |       ||--------+-------|| eggs   |   451 || more   |    42 || spam   |       |+--------+-------+rsttables:>>>print(tabulate(table,headers,tablefmt="rst"))======  =====item      qtyname======  =====eggs      451more       42spam======  =====Multiline cells are not well-supported for the other table formats.Automating MultilinesWhile tabulate supports data passed in with multilines entries explicitly provided,
it also provides some support to help manage this work internally.Themaxcolwidthsargument is a list where each entry specifies the max width for
it'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.UseNonefor 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 typically
the 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 linesOne 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 the
linebetweenrows, linebelowheader, linebelow, lineabove or just a simple empty line when none is defined for the formatter>>> from tabulate import tabulate, SEPARATING_LINE

table = [["Earth",6371],
         ["Mars",3390],
         SEPARATING_LINE,
         ["Moon",1737]]
print(tabulate(table, tablefmt="simple"))
-----  ----
Earth  6371
Mars   3390
-----  ----
Moon   1737
-----  ----Usage of the command line utilityUsage: 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 considerationsSuch features as decimal point alignment and trying to parse everything
as a number imply thattabulate:has to "guess" how to print a particular tabular data typeneeds to keep the entire table in-memoryhas to "transpose" the table twicedoes much more work than it may appearIt may not be suitable for serializing really big tables (but who's
going to do that, anyway?) or printing tables in performance sensitive
applications.tabulateis about two orders of magnitude slower than
simply joining lists of values with a tab, comma, or other separator.At the same time,tabulateis comparable to other table
pretty-printers. Given a 10x10 table (a list of lists) of mixed text and
numeric data,tabulateappears to be slower thanasciitable, and
faster thanPrettyTableandtexttableThe following mini-benchmark
was run in Python 3.8.2 in Ubuntu 20.04:==================================  ==========  ===========
Table formatter                       time, μs    rel. time
==================================  ==========  ===========
csv to StringIO                            9.0          1.0
join with tabs and newlines               10.7          1.2
asciitable (0.8.0)                       174.6         19.4
tabulate (0.8.10)                        385.0         42.8
tabulate (0.8.10, WIDE_CHARS_MODE)       509.1         56.5
PrettyTable (3.3.0)                      827.7         91.9
texttable (1.6.4)                        952.1        105.7
==================================  ==========  ===========Version historyThe full version history can be found at thechangelog.How to contributeContributions should include tests and an explanation for the changes
they propose. Documentation (examples, docstrings, README.md) should be
updated accordingly.This project usespytesttesting
framework andtoxto automate testing in
different environments. Add tests to one of the files in thetest/folder.To run tests on all supported Python versions, make sure all Python
interpreters,pytestandtoxare installed, then runtoxin the root
of the project source tree.On Linuxtoxexpects to find executables likepython3.7,python3.8etc.
On Windows it looks forC:\Python37\python.exe,C:\Python38\python.exeetc. 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.7.12
 pyenv install 3.8.12
 ...Don't forget to change yourPATHso thattoxknows how to find all the installed versions. Something likeexport PATH="${PATH}:${HOME}/.pyenv/shims"To test only some Python environments, use-eoption. For example, to
test only against Python 3.7 and Python 3.10, run:tox-epy37,py310in the root of the project source tree.To enable NumPy and Pandas tests, run:tox-epy37-extra,py310-extra(this may take a long time the first time, because NumPy and Pandas will
have to be installed in the new virtual environments)To fix code formatting:tox-elintSeetox.inifile to learn how to use to test
individual Python versions.ContributorsSergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill
Ryder, Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg
(anonymous), Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett,
Amjith Ramanujam, Jan Schulz, Simon Percivall, Javier Santacruz
López-Cepero, Sam Denton, Alexey Ziyangirov, acaird, Cesar Sanchez,
naught101, John Vandenberg, Zack Dever, Christian Clauss, Benjamin
Maier, 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.