API Reference#

table2ascii#

table2ascii.table2ascii(header=None, body=None, footer=None, *, first_col_heading=False, last_col_heading=False, column_widths=None, alignments=None, cell_padding=1, style=TableStyle(top_left_corner='╔', top_and_bottom_edge='═', heading_col_top_tee='╦', top_tee='═', top_right_corner='╗', left_and_right_edge='║', heading_col_sep='║', col_sep=' ', heading_row_left_tee='╟', heading_row_sep='─', heading_col_heading_row_cross='╫', heading_row_cross='─', heading_row_right_tee='╢', row_left_tee=' ', row_sep=' ', heading_col_row_cross=' ', col_row_cross=' ', row_right_tee=' ', bottom_left_corner='╚', heading_col_bottom_tee='╩', bottom_tee='═', bottom_right_corner='╝', col_row_top_tee=' ', col_row_bottom_tee=' ', heading_row_top_tee='─', heading_row_bottom_tee='─', heading_col_body_row_top_tee=' ', heading_col_body_row_bottom_tee=' ', heading_col_heading_row_top_tee='╥', heading_col_heading_row_bottom_tee='╨'), use_wcwidth=True)#

Convert a 2D Python table to ASCII text

Changed in version 1.0.0: Added the use_wcwidth parameter defaulting to True.

Parameters
  • header (Optional[Sequence[SupportsStr]]) – List of column values in the table’s header row. All values should be str or support str conversion. If not specified, the table will not have a header row.

  • body (Optional[Sequence[Sequence[SupportsStr]]]) – 2-dimensional list of values in the table’s body. All values should be str or support str conversion. If not specified, the table will not have a body.

  • footer (Optional[Sequence[SupportsStr]]) – List of column values in the table’s footer row. All values should be str or support str conversion. If not specified, the table will not have a footer row.

  • first_col_heading (bool) – Whether to add a header column separator after the first column. Defaults to False.

  • last_col_heading (bool) – Whether to add a header column separator before the last column. Defaults to False.

  • column_widths (Optional[Sequence[Optional[int]]]) – List of widths in characters for each column. Any value of None indicates that the column width should be determined automatically. If None is passed instead of a Sequence, all columns will be automatically sized. Defaults to None.

  • alignments (Optional[Sequence[Alignment]]) – List of alignments for each column (ex. [Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT]). If not specified or set to None, all columns will be center-aligned. Defaults to None.

  • cell_padding (int) – The minimum number of spaces to add between the cell content and the column separator. If set to 0, the cell content will be flush against the column separator. Defaults to 1.

  • style (TableStyle) – Table style to use for styling (preset styles can be imported). Defaults to double_thin_compact.

  • use_wcwidth (bool) – Whether to use wcwidth.wcswidth() to determine the width of each cell instead of len(). The wcswidth() function takes into account double-width characters (East Asian Wide and East Asian Fullwidth) and zero-width characters (combining characters, zero-width space, etc.), whereas len() determines the width solely based on the number of characters in the string. Defaults to True.

Return type

str

Returns

The generated ASCII table

Alignment#

enum table2ascii.Alignment(value)#

Enum for text alignment types within a table cell

Example:

from table2ascii import Alignment, table2ascii

table2ascii(
    header=["Product", "Category", "Price", "In Stock"],
    body=[
        ["Milk", "Dairy", "$2.99", "Yes"],
        ["Cheese", "Dairy", "$10.99", "No"],
        ["Apples", "Produce", "$0.99", "Yes"],
    ],
    alignments=[Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT, Alignment.LEFT],
)

"""
╔════════════════════════════════════════╗
║ Product   Category    Price   In Stock ║
╟────────────────────────────────────────╢
║ Milk       Dairy      $2.99   Yes      ║
║ Cheese     Dairy     $10.99   No       ║
║ Apples    Produce     $0.99   Yes      ║
╚════════════════════════════════════════╝
"""
Member Type

int

Valid values are as follows:

LEFT = <Alignment.LEFT: 0>#
CENTER = <Alignment.CENTER: 1>#
RIGHT = <Alignment.RIGHT: 2>#

Merge#

enum table2ascii.Merge(value)#

Enum for merging table cells

Using Merge.LEFT in a table cell will merge the cell it is used in with the cell to its left.

In the case that the contents of the merged cell are longer than the combined widths of the unmerged cells in the rows above and below, the merged cell will be wrapped onto multiple lines. The column_widths option can be used to control the widths of the unmerged cells.

Example:

from table2ascii import Merge, PresetStyle, table2ascii

table2ascii(
    header=["Name", "Price", "Category", "Stock"],
    body=[["Milk", "$2.99", "N/A", Merge.LEFT]],
    footer=["Description", "Milk is a nutritious beverage", Merge.LEFT, Merge.LEFT],
    style=PresetStyle.double_box,
)

"""
╔═════════════╦═══════╦══════════╦═══════╗
║    Name     ║ Price ║ Category ║ Stock ║
╠═════════════╬═══════╬══════════╩═══════╣
║    Milk     ║ $2.99 ║       N/A        ║
╠═════════════╬═══════╩══════════════════╣
║ Description ║   Milk is a nutritious   ║
║             ║         beverage         ║
╚═════════════╩══════════════════════════╝
"""

New in version 1.0.0.

Valid values are as follows:

LEFT = <Merge.LEFT: 0>#

PresetStyle#

class table2ascii.PresetStyle#

Importable preset styles for more easily selecting a TableStyle.

See the Preset Styles for more information on the available styles.

Example:

from table2ascii import PresetStyle, table2ascii

table2ascii(
    header=["Name", "Price", "Category", "Stock"],
    body=[["Milk", "$2.99", "Dairy", 10]],
    style=PresetStyle.ascii_double,  # Use any available preset style
)

"""
+---------------------------------+
| Name   Price   Category   Stock |
+=================================+
| Milk   $2.99    Dairy      10   |
+---------------------------------+
"""

TableStyle#

class table2ascii.TableStyle(top_left_corner, top_and_bottom_edge, heading_col_top_tee, top_tee, top_right_corner, left_and_right_edge, heading_col_sep, col_sep, heading_row_left_tee, heading_row_sep, heading_col_heading_row_cross, heading_row_cross, heading_row_right_tee, row_left_tee, row_sep, heading_col_row_cross, col_row_cross, row_right_tee, bottom_left_corner, heading_col_bottom_tee, bottom_tee, bottom_right_corner, col_row_top_tee, col_row_bottom_tee, heading_row_top_tee, heading_row_bottom_tee, heading_col_body_row_top_tee, heading_col_body_row_bottom_tee, heading_col_heading_row_top_tee, heading_col_heading_row_bottom_tee)#

Class for storing information about a table style

Parts of the table labeled alphabetically from A to V:

ABBBBBCBBBBBDBBBBBDBBBBBDBBBBBE
F     G     H     H     H     F
IJJJJJKJJJJJLJJJJJLJJJJJLJJJJJM
F     G     H     H     H     F
NOOOOOPOOOOOQOOOOOQOOOOOQOOOOOR
F     G     H     H     H     F
IJJJJJKJJJJJLJJJJJLJJJJJLJJJJJM
F     G     H     H     H     F
SBBBBBTBBBBBUBBBBBUBBBBBUBBBBBV

How the theme is displayed using double_thin_box as an example:

╔═════╦═════╤═════╤═════╤═════╗
║  #  ║  G  │  H  │  R  │  S  ║
╠═════╬═════╪═════╪═════╪═════╣
║  1  ║ 30  │ 40  │ 35  │ 30  ║
╟─────╫─────┼─────┼─────┼─────╢
║  2  ║ 30  │ 40  │ 35  │ 30  ║
╠═════╬═════╪═════╪═════╪═════╣
║ SUM ║ 130 │ 140 │ 135 │ 130 ║
╚═════╩═════╧═════╧═════╧═════╝

In addition to the parts above, W-Z and the four fields that follow (labeled 0-3) are used for top and bottom edges of merged cells as shown:

╔══════════════╤══════╤══════╗
║    Header    │      │      ║
╠══════[2]═════╪═════[Z]═════╣
║       ║      │             ║
╟──────[1]─────┼─────────────╢
║              │             ║
╟──────[0]─────┼─────[W]─────╢
║       ║      │      │      ║
╟───────╫──────┼─────[X]─────╢
║       ║      │             ║
╠══════[3]═════╪═════[Y]═════╣
║    Footer    │      │      ║
╚══════════════╧══════╧══════╝

[W] = ┬ [X] = ┴ [Y] = ╤ [Z] = ╧
[0] = ╥ [1] = ╨ [2] = ╦ [3] = ╩

Changed in version 1.0.0: Added fields for edges of merged cells:

col_row_top_tee, col_row_bottom_tee, heading_row_top_tee, heading_row_bottom_tee, heading_col_body_row_top_tee, heading_col_body_row_bottom_tee, heading_col_heading_row_top_tee, heading_col_heading_row_bottom_tee

classmethod from_string(string)#

Create a TableStyle from a string

Changed in version 1.0.0: The string will be padded on the right with spaces if it is too short and TableStyleTooLongError will be raised if it is too long.

Parameters

string (str) – The string to create the TableStyle from

Return type

TableStyle

Returns

A TableStyle object

Example:

TableStyle.from_string("╔═╦╤╗║║│╠═╬╪╣╟─╫┼╢╚╩╧╝┬┴╤╧╥╨╦╩")
Raises

TableStyleTooLongError – If the string is too long

set(**kwargs)#

Set attributes of the TableStyle

Parameters

kwargs – The attributes to set

Return type

TableStyle

Returns

A TableStyle object with the attributes set

Example:

TableStyle().set(top_left_corner="╔", top_and_bottom_edge="═")

Exceptions#

exception table2ascii.exceptions.Table2AsciiError#

Base class for all table2ascii exceptions

exception table2ascii.exceptions.TableOptionError#

Base class for exceptions raised when an invalid option is passed when creating an ascii table

This class is a subclass of Table2AsciiError and ValueError.

exception table2ascii.exceptions.ColumnCountMismatchError#

Base class for exceptions raised when a parameter has an invalid number of columns

This class is a subclass of TableOptionError.

exception table2ascii.exceptions.FooterColumnCountMismatchError(footer, expected_columns)#

Exception raised when the number of columns in the footer does not match the number of columns in the header

This class is a subclass of ColumnCountMismatchError.

footer#

The footer that caused the error

Type

Sequence[SupportsStr]

expected_columns#

The number of columns that were expected

Type

int

exception table2ascii.exceptions.BodyColumnCountMismatchError(body, expected_columns)#

Exception raised when the number of columns in the body does not match the number of columns in the footer or header

This class is a subclass of ColumnCountMismatchError.

body#

The body that caused the error

Type

Sequence[Sequence[SupportsStr]]

expected_columns#

The number of columns that were expected

Type

int

first_invalid_row#

The first row with an invalid column count

Type

Sequence[SupportsStr]

exception table2ascii.exceptions.AlignmentCountMismatchError(alignments, expected_columns)#

Exception raised when the number of alignments does not match the number of columns in the table

This class is a subclass of ColumnCountMismatchError.

alignments#

The alignments that caused the error

Type

Sequence[Alignment]

expected_columns#

The number of columns that were expected

Type

int

exception table2ascii.exceptions.InvalidCellPaddingError(padding)#

Exception raised when the cell padding is invalid

This class is a subclass of TableOptionError.

padding#

The padding that caused the error

Type

int

exception table2ascii.exceptions.ColumnWidthsCountMismatchError(column_widths, expected_columns)#

Exception raised when the number of column widths does not match the number of columns in the table

This class is a subclass of ColumnCountMismatchError.

column_widths#

The column widths that caused the error

Type

Sequence[Optional[int]]

expected_columns#

The number of columns that were expected

Type

int

exception table2ascii.exceptions.ColumnWidthTooSmallError(column_index, column_width, min_width=None)#

Exception raised when the column width is smaller than the minimum number of characters that are required to display the content

This class is a subclass of TableOptionError.

column_index#

The index of the column that caused the error

Type

int

column_width#

The column width that caused the error

Type

int

min_width#

The minimum width that is allowed

Type

int

exception table2ascii.exceptions.InvalidColumnWidthError(column_index, column_width, min_width=None)#

Exception raised when the column width is invalid

This class is a subclass of ColumnWidthTooSmallError.

exception table2ascii.exceptions.InvalidAlignmentError(alignment)#

Exception raised when an invalid value is passed for an Alignment

This class is a subclass of TableOptionError.

alignment#

The alignment value that caused the error

Type

Any

exception table2ascii.exceptions.TableStyleTooLongError(string, max_characters)#

Exception raised when the number of characters passed in the string for creating the table style exceeds the number of parameters that the table style accepts

This class is a subclass of Table2AsciiError and ValueError.

string#

The string that caused the error

Type

str

max_characters#

The maximum number of characters that are allowed

Type

int

Warnings#

class table2ascii.exceptions.TableStyleTooShortWarning(string, max_characters)#

Warning raised when the number of characters passed in the string for creating the table style is fewer than the number of parameters that the table style accepts

This class is a subclass of UserWarning.

It can be silenced using warnings.filterwarnings().

string#

The string that caused the warning

Type

str

max_characters#

The number of characters that TableStyle accepts

Type

int