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 bestr
or supportstr
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 bestr
or supportstr
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 bestr
or supportstr
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 toFalse
.last_col_heading (
bool
) – Whether to add a header column separator before the last column.Defaults toFalse
.column_widths (
Optional
[Sequence
[Optional
[int
]]]) – List of widths in characters for each column. Any value ofNone
indicates that the column width should be determined automatically. IfNone
is passed instead of aSequence
, all columns will be automaticallysized. Defaults toNone
.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 toNone
, all columns will be center-aligned.Defaults toNone
.Changed in version 1.1.0:
alignments
can now also be specified as a singleAlignment
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 alignmentto apply to all columns. This argument can be used to override the alignment of numbers andis 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 toNone
, numbers will be aligned based on thealignments
argument.Defaults toNone
.New in version 1.1.0.
cell_padding (
int
) – The minimum number of spaces to add between the cell content and the columnseparator. If set to0
, the cell content will be flush against the column separator.Defaults to1
.style (
TableStyle
) – Table style to use for styling (preset styles can be imported).Defaults todouble_thin_compact.use_wcwidth (
bool
) –Whether to use
wcwidth.wcswidth()
to determine the width of each cell instead oflen()
. Thewcswidth()
function takes into account double-width characters(East Asian Wide and East Asian Fullwidth) and zero-width characters (combining characters,zero-width space, etc.), whereaslen()
determines the width solely based on the number ofcharacters in the string. Defaults toTrue
.New in version 1.0.0.
- Return type
- Returns
The generated ASCII table
Alignment#
- enumtable2ascii.Alignment(value)#
Enum for text alignment types within a table cell
A list of alignment types can be used to align each column individually:
fromtable2asciiimportAlignment,table2asciitable2ascii(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 pointalignments=[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 leftnumber_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 thenumber_alignments
argument totable2ascii()
,all non-numeric values will be aligned according to thealignments
argument.If theDECIMAL
alignment type is used in thealignments
argument,all non-numeric values will be aligned to the center.Numeric values include integers, floats, and strings containing onlydecimal
characters and at most one decimal point.Changed in version 1.1.0:Added
DECIMAL
alignment – align decimal numbers such thatthe decimal point is aligned with the decimal point of all other numbersin the same column.- Member Type
Valid values are as follows:
- LEFT=<Alignment.LEFT:0>#
- CENTER=<Alignment.CENTER:1>#
- RIGHT=<Alignment.RIGHT:2>#
- DECIMAL=<Alignment.DECIMAL:3>#
Merge#
- enumtable2ascii.Merge(value)#
Enum for merging table cells
Using
Merge.LEFT
in a table cell will merge the cell it is used inwith the cell to its left.In the case that the contents of the merged cell are longer than thecombined 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:
fromtable2asciiimportMerge,PresetStyle,table2asciitable2ascii(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#
- classtable2ascii.PresetStyle#
Importable preset styles for more easily selecting aTableStyle.
See thePreset Styles for more information on the available styles.
Example:
fromtable2asciiimportPresetStyle,table2asciitable2ascii(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#
- classtable2ascii.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:
ABBBBBCBBBBBDBBBBBDBBBBBDBBBBBEFGHHHFIJJJJJKJJJJJLJJJJJLJJJJJLJJJJJMFGHHHFNOOOOOPOOOOOQOOOOOQOOOOOQOOOOORFGHHHFIJJJJJKJJJJJLJJJJJLJJJJJLJJJJJMFGHHHFSBBBBBTBBBBBUBBBBBUBBBBBUBBBBBV
How the theme is displayed usingdouble_thin_boxas 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
- classmethodfrom_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 shortand
TableStyleTooLongError
will beraised if it is too long.- Parameters
string (
str
) – The string to create the TableStyle from- Return type
- 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
- Returns
A TableStyle object with the attributes set
Example:
TableStyle.from_string("~"*30).set(left_and_right_edge="",col_sep="")
Exceptions#
- exceptiontable2ascii.Table2AsciiError#
Base class for all table2ascii exceptions
- exceptiontable2ascii.TableOptionError#
Base class for exceptions raised when an invalid optionis passed when creating an ascii table
This class is a subclass of
Table2AsciiError
andValueError
.
- exceptiontable2ascii.ColumnCountMismatchError#
Base class for exceptions raised when a parameter has aninvalid number of columns
This class is a subclass of
TableOptionError
.
- exceptiontable2ascii.FooterColumnCountMismatchError(footer,expected_columns)#
Exception raised when the number of columns in the footerdoes not match the number of columns in the header
This class is a subclass of
ColumnCountMismatchError
.- footer#
The footer that caused the error
- Type
- exceptiontable2ascii.BodyColumnCountMismatchError(body,expected_columns)#
Exception raised when the number of columns in the bodydoes 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
- first_invalid_row#
The first row with an invalid column count
- Type
- exceptiontable2ascii.AlignmentCountMismatchError(alignments,expected_columns)#
Exception raised when the number of alignments does not matchthe number of columns in the table
This class is a subclass of
ColumnCountMismatchError
.
- exceptiontable2ascii.InvalidCellPaddingError(padding)#
Exception raised when the cell padding is invalid
This class is a subclass of
TableOptionError
.
- exceptiontable2ascii.ColumnWidthsCountMismatchError(column_widths,expected_columns)#
Exception raised when the number of column widths does not matchthe number of columns in the table
This class is a subclass of
ColumnCountMismatchError
.
- exceptiontable2ascii.ColumnWidthTooSmallError(column_index,column_width,min_width=None)#
Exception raised when the column width is smaller than the minimumnumber of characters that are required to display the content
This class is a subclass of
TableOptionError
.
- exceptiontable2ascii.InvalidColumnWidthError(column_index,column_width,min_width=None)#
Exception raised when the column width is invalid
This class is a subclass of
ColumnWidthTooSmallError
.
- exceptiontable2ascii.InvalidAlignmentError(alignment)#
Exception raised when an invalid value is passed for an
Alignment
This class is a subclass of
TableOptionError
.
- exceptiontable2ascii.TableStyleTooLongError(string,max_characters)#
Exception raised when the number of characters passed in the stringfor creating the table style exceeds the number of parameters that thetable style accepts
This class is a subclass of
Table2AsciiError
andValueError
.
Warnings#
- classtable2ascii.TableStyleTooShortWarning(string,max_characters)#
Warning raised when the number of characters passed in the stringfor creating the table style is fewer than the number of parametersthat the table style accepts
This class is a subclass of
UserWarning
.It can be silenced using
warnings.filterwarnings()
.- max_characters#
The number of characters that
TableStyle
accepts- Type