from prettytable import PrettyTable
table = PrettyTable()
and you want to put some data into it. You have a few options.
Row by row
You can add data one row at a time. To do this you can set the field names first using
the field_names attribute, and then add the rows one at a time using the add_row
method:
You can add data one column at a time as well. To do this you use the add_column
method, which takes two arguments - a string which is the name for the field the column
you are adding corresponds to, and a list or tuple which contains the column data:
If you really want to, you can even mix and match add_row and add_column and build
some of your table in one way and some of it in the other. Tables built this way are
kind of confusing for other people to read, though, so don't do this unless you have a
good reason.
Importing data from a CSV file
If you have your table data in a comma-separated values file (.csv), you can read this
data into a PrettyTable like this:
from prettytable import from_csv
with open("myfile.csv") as fp:
mytable = from_csv(fp)
Importing data from a database cursor
If you have your table data in a database which you can access using a library which
confirms to the Python DB-API (e.g. an SQLite database accessible using the sqlite
module), then you can build a PrettyTable using a cursor object, like this:
There are three ways to get data out of a PrettyTable, in increasing order of
completeness:
The del_row method takes an integer index of a single row to delete.
The del_column method takes a field name of a single column to delete.
The clear_rows method takes no arguments and deletes all the rows in the table - but
keeps the field names as they were so you that you can repopulate it with the same
kind of data.
The clear method takes no arguments and deletes all rows and all field names. It's
not quite the same as creating a fresh table instance, though - style related
settings, discussed later, are maintained.
Displaying your table in ASCII form
PrettyTable's main goal is to let you print tables in an attractive ASCII form, like
this:
You can print tables like this to stdout or get string representations of them.
Printing
To print a table in ASCII form, you can just do this:
print(table)
The old table.printt() method from versions 0.5 and earlier has been removed.
To pass options changing the look of the table, use the get_string() method documented
below:
print(table.get_string())
Stringing
If you don't want to actually print your table in ASCII form but just get a string
containing what would be printed if you use print(table), you can use the
get_string method:
mystring = table.get_string()
This string is guaranteed to look exactly the same as what would be printed by doing
print(table). You can now do all the usual things you can do with a string, like write
your table to a file or insert it into a GUI.
The table can be displayed in several different formats using get_formatted_string by
changing the out_format=<text|html|json|csv|latex|mediawiki>. This function passes
through arguments to the functions that render the table, so additional arguments can be
given. This provides a way to let a user choose the output formatting.
If you have a large table and want to split it into multiple pages, you can use the
paginate method. This method splits the table into pages of a specified length and
separates them with a line break character (by default, a form feed character \f):
The page_length parameter controls how many rows appear on each page (default: 58).
The line_break parameter specifies the string used to separate pages (default: "\f"
form feed). You can also pass any keyword arguments that are accepted by get_string()
to control the formatting of each page:
+-----------+------------+
| City name | Population |
+-----------+------------+
| Adelaide | 1158259 |
| Brisbane | 1857594 |
| Darwin | 120900 |
| Hobart | 205556 |
| Melbourne | 3806092 |
| Perth | 1554769 |
| Sydney | 4336374 |
+-----------+------------+
The start and end arguments take the index of the first and last row to print
respectively. Note that the indexing works like Python list slicing - to print the 2nd,
3rd and 4th rows of the table, set start to 1 (the first row is row 0, so the second
is row 1) and set end to 4 (the index of the 4th row, plus 1):
print(table.get_string(start=1, end=4))
prints:
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
| Hobart | 1357 | 205556 | 619.5 |
+-----------+------+------------+-----------------+
Filtering your table
You can make sure that your tables are filtered by giving get_string a row_filter
keyword argument, which must be a function with one argument row returning a Boolean
value. The row is the list of fields in a row.
For example, to print the example table we built earlier of Australian capital city
data, so that cities with a population of at least 1,000,000, we can do this:
By default, all columns in a table are centre aligned.
All columns at once
You can change the alignment of all the columns in a table at once by assigning a one
character string to the align attribute. The allowed strings are "l", "r" and
"c" for left, right and centre alignment, respectively:
You can also change the alignment of individual columns based on the corresponding field
name by treating the align attribute as if it were a dictionary.
You can make sure that your ASCII tables are produced with the data sorted by one
particular field by giving get_string a sortby keyword argument, which must be a
string containing the name of one field.
For example, to print the example table we built earlier of Australian capital city
data, so that the most populated city comes last, we can do this:
All three tables printed by this code will be sorted by population (you could do
table.reversesort = True as well, if you wanted). The behaviour will persist until you
turn it off:
table.sortby = None
If you want to specify a custom sorting function, you can use the sort_key keyword
argument as Pythons sorted()key parameter. The value of the sort_key parameter
should be a function (or other callable) that takes a single argument and returns a key
to use for sorting purposes.
If your table has n columns, each list will have n+1 elements. Each list corresponds to
one row of the table. The first element will be whatever data is in the relevant row, in
the column specified by the sort_by argument. The remaining n elements are the data in
each of the table's columns, in order, including a repeated instance of the data in the
sort_by column.
Adding sections to a table
You can divide your table into different sections using the add_divider method or
divider argument to add_row() or even to add_rows(). This will add a dividing line
into the table under the row who has this field set. So we can set up a table like this:
+-------------------------------------------------+
| Australian Cities |
| Population Data |
+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
| Adelaide | 1295 | 1158259 | 600.5 |
| Brisbane | 5905 | 1857594 | 1146.4 |
| Darwin | 112 | 120900 | 1714.7 |
+-----------+------+------------+-----------------+
Each line of the title is centered and bordered independently. Multiline titles also
work with HTML output (using <br> in the <caption> tag) and Markdown output.
Changing the appearance of your table - the easy way
By default, PrettyTable produces ASCII tables that look like the ones used in SQL
database shells. But it can print them in a variety of other formats as well. If the
format you want to use is common, PrettyTable makes this easy for you to do using the
set_style method. If you want to produce an uncommon table, you'll have to do things
slightly harder (see later).
Setting a table style
You can set the style for your table using the set_style method before any calls to
print or get_string. Here's how to print a table in Markdown format:
from prettytable import TableStyle
table.set_style(TableStyle.MARKDOWN)
print(table)
In addition to MARKDOWN you can use these in-built styles:
DEFAULT - The default look, used to undo any style changes you may have made
PLAIN_COLUMNS - A borderless style that works well with command line programs for
columnar data
MSWORD_FRIENDLY - A format which works nicely with Microsoft Word's "Convert to
table" feature
RST - A table style that produces reStructuredText
grid tables
SINGLE_BORDER and DOUBLE_BORDER - Styles that use continuous single/double border
lines with Box drawing characters for a fancier display on terminal
Other styles are likely to appear in future releases.
Changing the appearance of your table - the hard way
If you want to display your table in a style other than one of the in-built styles
listed above, you'll have to set things up the hard way.
Don't worry, it's not really that hard!
Style options
PrettyTable has a number of style options which control various aspects of how tables
are displayed. You have the freedom to set each of these options individually to
whatever you prefer. The set_style method just does this automatically for you.
Table-specific options are:
Option
Details
HEADER, ALL, NONE
These are variables defined inside the prettytable module so make sure you import them or use prettytable.FRAME etc.
_horizontal_align_char
Single character string used to indicate column alignment in horizontal lines. Default: : for Markdown, otherwise None.
border
A Boolean option (must be True or False). Controls whether a border is drawn inside and around the table.
bottom_junction_char
single character string used to draw bottom line junctions. Default: junction_char.
bottom_left_junction_char
Single character string used to draw bottom-left line junctions. Default: junction_char.
bottom_right_junction_char
Single character string used to draw bottom-right line junctions. Default: junction_char.
break_on_hyphens
Whether long lines are wrapped on hyphens. Default: True.
header
A Boolean option (must be True or False). Controls whether the first row of the table is a header showing the names of all the fields.
horizontal_char
Single character string used to draw horizontal lines. Default: -.
hrules
Controls printing of horizontal rules after rows. Allowed values: FRAME, HEADER, ALL, NONE.
junction_char
Single character string used to draw line junctions. Default: +.
left_junction_char
Single character string used to draw left line junctions. Default: junction_char.
left_padding_width
Number of spaces on left-hand side of column data.
max_table_width
Number of characters used for the maximum total table width.
min_table_width
Number of characters used for the minimum total table width.
padding_width
Number of spaces on either side of column data (only used if left and right paddings are None).
preserve_internal_border
A Boolean option (must be True or False). Controls whether borders are still drawn within the table even when border=False.
right_junction_char
Single character string used to draw right line junctions. Default: junction_char.
right_padding_width
Number of spaces on right-hand side of column data.
top_junction_char
Single character string used to draw top line junctions. Default: junction_char.
top_left_junction_char
Single character string used to draw top-left line junctions. Default: junction_char.
top_right_junction_char
Single character string used to draw top-right line junctions. Default: junction_char.
use_header_width
A Boolean option (must be True or False). Controls whether the width of the header is used for computing column width. Default: True.
vertical_char
Single character string used to draw vertical lines. Default: |.
vrules
Controls printing of vertical rules between columns. Allowed values: FRAME, ALL, NONE.
For options that can be set individually for each column (align, valign,
custom_format, max_width, min_width, int_format, float_format, none_format)
you can either set a value, that applies to all columns or set a dict with column names
and individual values.
Column-specific options are:
Option
Details
align
Controls alignment of fields, one of "l", "c", or "r" or a dictionary with column and value.
custom_format
Set any format, by setting a function that gets the original value,the formatted representation and returns the new string. E.g. pf.custom_format["my_col_int"] = lambda f, v: f"{v:,}". The type of the callable is Callable[[str, Any], str]. This also takes a dictionary with column and function.
float_format
A string which controls the way floating point data is printed or a dictionary with column and value. This works like: print("%<float_format>f" % data).
int_format
A string which controls the way integer data is printed or a dictionary with column and value. This works like: print("%<int_format>d" % data).
max_width
Number of characters used for maximum width of a column or a dictionary with column and value.
min_width
Number of characters used for minimum width of a column or a dictionary with column and value.
none_format
Representation of None values or a dictionary with column and value.
valign
Controls vertical alignment of fields, one of "t", "m", or "b" or a dictionary with column and value.
You can set the style options to your own settings in two ways:
Setting style options for the long term
If you want to print your table with a different style several times, you can set your
option for the long term just by changing the appropriate attributes. If you never want
your tables to have borders you can do this:
Neither of the 3 tables printed by this will have borders, even if you do things like
add extra rows in between them. The lack of borders will last until you do:
table.border = True
to turn them on again. This sort of long-term setting is exactly how set_style works.
set_style just sets a bunch of attributes to pre-set values for you.
Note that if you know what style options you want at the moment you are creating your
table, you can specify them using keyword arguments to the constructor. For example, the
following two code blocks are equivalent:
If you don't want to make long-term style changes by changing an attribute like in the
previous section, you can make changes that last for just one get_string by giving
those methods keyword arguments. To print two "normal" tables with one borderless table
between them, you could do this:
The custom_format attribute allows you to define a function for custom cell value
formatting. For example, the following code demonstrates how to apply a single function
across all columns to display strings in blue, positive numbers in green, and
negative numbers in red, all with a precision of two decimal places. Your custom
function can also inspect the field parameter to apply field-specific formatting.
from prettytable import PrettyTable
from typing import Any
from termcolor import colored
def _colored(field: str, val: Any) -> str:
if isinstance(val, (int, float)):
if val >= 0:
return colored(f"{val:.2f}", "green")
return colored(f"{val:.2f}", "red")
elif isinstance(val, str):
return colored(val, "blue")
return f"{val}"
table = PrettyTable(("Name", "Overtime"))
table.custom_format = _colored
for row in [["John Doe", 5.0], ["Jane Smith", -2.0]]:
table.add_row([row[0], row[1]])
print(table)
Changing the appearance of your table - with colors!
PrettyTable has the functionality of printing your table with ANSI color codes. This
includes support for most Windows versions through
Colorama. To get started, import the ColorTable
class instead of PrettyTable.
The ColorTable class can be used the same as PrettyTable, but it adds an extra
property. You can now specify a custom theme that will format your table with colors.
from prettytable.colortable import ColorTable, Themes
table = ColorTable(theme=Themes.OCEAN)
print(table)
Creating a custom theme
The Theme class allows you to customize both the characters and colors used in your
table.
Argument
Description
default_color
The color to use as default
vertical_char, horizontal_char, and junction_char
The characters used for creating the outline of the table
vertical_color, horizontal_color, and junction_color
The colors used to style each character.
Note: Colors are formatted with the Theme.format_code(s: str) function. It
accepts a string. If the string starts with an escape code (like \x1b) then it will
return the given string. If the string is just whitespace, it will return "". If the
string is a number (like "34"), it will automatically format it into an escape code.
I recommend you look into the source code for more information.
Displaying your table in JSON
PrettyTable will also print your tables in JSON, as a list of fields and an array of
rows. Just like in ASCII form, you can actually get a string representation - just use
get_json_string().
Displaying your table in MediaWiki markup
PrettyTable can also print your tables in MediaWiki table markup, making it easy to
format tables for wikis. Similar to the ASCII format, you can get a string
representation using get_mediawiki_string().
Displaying your table in HTML form
PrettyTable will also print your tables in HTML form, as <table>s. Just like in ASCII
form, you can actually get a string representation - just use get_html_string(). HTML
printing supports the fields, start, end, sortby and reversesort arguments in
exactly the same way as ASCII printing.
Styling HTML tables
By default, PrettyTable outputs HTML for "vanilla" tables. The HTML code is quite
simple. It looks like this:
If you like, you can ask PrettyTable to do its best to mimic the style options that your
table has set using inline CSS. This is done by giving a format=True keyword argument
to get_html_string method. Note that if you always want to print formatted HTML you
can do:
table.format = True
and the setting will persist until you turn it off.
Just like with ASCII tables, if you want to change the table's style for just one
get_html_string you can pass those methods' keyword arguments - exactly like print
and get_string.
Setting HTML attributes
You can provide a dictionary of HTML attribute name/value pairs to the get_html_string
method using the attributes keyword argument. This lets you specify common HTML
attributes like id and class that can be used for linking to your tables or
customising their appearance using CSS. For example:
By default, PrettyTable will escape the data contained in the header and data fields
when sending output to HTML. This can be disabled by setting the escape_header and
escape_data to false. For example: