API Reference#

table2ascii#

table2ascii.table2ascii(header=None, body=None, footer=None, *, first_col_heading=False, last_col_heading=False, column_widths=None, alignments=None, number_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

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 (Union[Sequence[Alignment], Alignment, None]) –

    List of alignments for each column (ex. [Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT, Alignment.DECIMAL]) or a single alignment to apply to all columns (ex. Alignment.LEFT). If not specified or set to None, all columns will be center-aligned. Defaults to None.

    Changed in version 1.1.0: alignments can now also be specified as a single Alignment value to apply to all columns.

  • number_alignments (Union[Sequence[Alignment], Alignment, None]) –

    List of alignments for numeric values in each column or a single alignment to apply to all columns. This argument can be used to override the alignment of numbers and is ignored for non-numeric values. Numeric values include integers, floats, and strings containing only decimal characters and at most one decimal point. If not specified or set to None, numbers will be aligned based on the alignments argument. Defaults to None.

    New in version 1.1.0.

  • 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.

    New in version 1.0.0.

Return type

str

Returns

The generated ASCII table

Alignment#

enum table2ascii.Alignment(value)#

Enum for text alignment types within a table cell

A list of alignment types can be used to align each column individually:

from table2ascii import Alignment, table2ascii

table2ascii(
    header=["Product", "Category", "Price", "Rating"],
    body=[
        ["Milk", "Dairy", "$2.99", "6.28318"],
        ["Cheese", "Dairy", "$10.99", "8.2"],
        ["Apples", "Produce", "$0.99", "10.00"],
    ],
    # Align the first column to the left, the second to the center,
    # the third to the right, and the fourth to the decimal point
    alignments=[Alignment.LEFT, Alignment.CENTER, Alignment.RIGHT, Alignment.DECIMAL],
)

"""
╔════════════════════════════════════════╗
║ Product   Category    Price    Rating  ║
╟────────────────────────────────────────╢
║ Milk       Dairy      $2.99    6.28318 ║
║ Cheese     Dairy     $10.99    8.2     ║
║ Apples    Produce     $0.99   10.00    ║
╚════════════════════════════════════════╝
"""

A single alignment type can be used to align all columns:

table2ascii(
    header=["First Name", "Last Name", "Age"],
    body=[
        ["John", "Smith", 30],
        ["Jane", "Doe", 28],
    ],
    alignments=Alignment.LEFT,  # Align all columns to the left
    number_alignments=Alignment.RIGHT,  # Align all numeric values to the right
)

"""
╔══════════════════════════════╗
║ First Name   Last Name   Age ║
╟──────────────────────────────╢
║ John         Smith        30 ║
║ Jane         Doe          28 ║
╚══════════════════════════════╝
"""

Note

If DECIMAL is used in the number_alignments argument to table2ascii(), all non-numeric values will be aligned according to the alignments argument. If the DECIMAL alignment type is used in the alignments argument, all non-numeric values will be aligned to the center. Numeric values include integers, floats, and strings containing only decimal characters and at most one decimal point.

Changed in version 1.1.0: Added DECIMAL alignment – align decimal numbers such that the decimal point is aligned with the decimal point of all other numbers in the same column.

Member Type

int

Valid values are as follows:

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

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.from_string("~" * 30).set(left_and_right_edge="", col_sep="")

Exceptions#

exception table2ascii.Table2AsciiError#

Base class for all table2ascii exceptions

exception table2ascii.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.ColumnCountMismatchError#

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

This class is a subclass of TableOptionError.

exception table2ascii.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.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.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.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.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.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.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.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.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.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

Annotations#

class table2ascii.SupportsStr(*args, **kwargs)#

An abstract base class (ABC) with one abstract method __str__()

abstractmethod __str__()#

Return a string representation of the object

Return type

str