PrettyTable
last modified November 18, 2026 Python 3.15
In this article we show how to use the Python PrettyTable module to generate
ASCII tables in Python. An ASCII table is a text table drawn with plain
characters such as +, -, and |, so it
can be printed in any terminal. The examples were run with PrettyTable 3.19.0
and ccxt 4.5.93 on Python 3.15.
PrettyTable
PrettyTable is a Python library for generating simple ASCII tables. It was inspired by the ASCII tables used in the PostgreSQL shell psql. We can control many aspects of a table, such as the width of the column padding, the alignment of text, or the table border. We can sort data.
We can also choose which columns and rows are going to be displayed in the final output. PrettyTable can read data from CSV, HTML, or a database cursor and output data as ASCII, HTML, CSV, or JSON.
PrettyTable installation
PrettyTable is a third-party package, so it must be installed first. We install
it with the pip tool, which is the standard Python package
installer. The command downloads and installs the prettytable package
from the Python Package Index (PyPI). Once installed, the module can be imported
in any Python script.
$ pip install prettytable
Creating a table by rows
A table can be created with the add_row or add_column
methods. The field_names property holds the column headers. A row
is a list of values, one value per column.
from prettytable import PrettyTable x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x)
The example creates a PrettyTable with the add_row method. The
table is an object of the PrettyTable class; calling
print on it converts it to its ASCII text form.
from prettytable import PrettyTable
From the module, we import the PrettyTable class.
x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
We create an empty table and set the header names. The header names are the values shown in the first row of the table.
x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4])
Each call to add_row appends one row. The number of values must
match the number of column names.
print(x)
In the end, we print the table to the console. The default alignment centers the values. Each column is wide enough for its longest value, and the padding on both sides is one space.
$ python create_by_row.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+
Creating a table by columns
In the next example, we create the same table with the add_column
method. Here we build the table column by column instead of row by row.
from prettytable import PrettyTable
x = PrettyTable()
column_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_column(column_names[0], ["Adelaide", "Brisbane", "Darwin",
"Hobart", "Sydney", "Melbourne", "Perth"])
x.add_column(column_names[1], [1295, 5905, 112, 1357, 2058, 1566, 5386])
x.add_column(column_names[2], [1158259, 1857594, 120900, 205556, 4336374,
3806092, 1554769])
x.add_column(column_names[3], [600.5, 1146.4, 1714.7, 619.5, 1214.8,
646.9, 869.4])
print(x)
The column name is the first parameter of the add_column
method, and the second parameter is the list of values in that column. Each
list must have the same length. The output is identical to the previous
example.
$ python create_by_column.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+
PrettyTable deleting rows
With del_row it is possible to delete a specific row.
The method takes the index of the row to be deleted. Indexing starts from zero,
so the first row has index 0 and the last row has index len(x.rows) - 1.
from prettytable import PrettyTable x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) x.del_row(6) x.del_row(5) x.del_row(4) x.del_row(3) print(x)
In the example, we delete the last four rows. We delete from the bottom up: after each deletion, the indexes of the rows below the deleted row do not change, so the indexes stay valid for the next call.
The first three rows are left in the output.
$ python delete_rows.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | +-----------+------+------------+-----------------+
PrettyTable clearing data
The clear_rows method deletes all rows from the table but keeps the
current column names. The clear method clears both rows and column
names, leaving an empty table.
from prettytable import PrettyTable x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) x.clear_rows() print(x)
The example clears all rows from the table.
This is the output of the example. The header of the table is kept, but no data rows remain.
$ python clear_rows.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ +-----------+------+------------+-----------------+
PrettyTable generation from CSV
The from_csv function generates a PrettyTable from CSV data. CSV
(comma-separated values) is a plain text format where each line is one row and
the values are separated by commas. The function takes an open file object.
"City name", "Area", "Population", "Annual Rainfall" "Adelaide", 1295, 1158259, 600.5 "Brisbane", 5905, 1857594, 1146.4 "Darwin", 112, 120900, 1714.7 "Hobart", 1357, 205556, 619.5 "Sydney", 2058, 4336374, 1214.8 "Melbourne", 1566, 3806092, 646.9 "Perth", 5386, 1554769, 869.4
The data.csv file contains values separated by commas. Note that
the first row holds the table column names. Values wrapped in double quotes are
read as text, and the remaining values are parsed by the CSV reader.
from prettytable import from_csv
with open("data.csv", "r") as fp:
x = from_csv(fp)
print(x)
The example opens data.csv and generates a PrettyTable from it
with from_csv. The with statement closes the file
automatically once the block ends.
$ python read_from_csv.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+
PrettyTable generation from database cursor
The from_db_cursor function generates a PrettyTable from a database
cursor. A cursor is an object that runs SQL queries and lets us read the result
rows. The first item of the cursor's description gives the column
names, which become the table header.
DROP TABLE IF EXISTS Cities;
CREATE TABLE Cities(Id INTEGER PRIMARY KEY, Name TEXT, Area INTEGER,
Population INTEGER, Rainfall REAL);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Adelaide", 1295, 1158259, 600.5);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Brisbane", 5905, 1857594, 1146.4);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Darwin", 112, 120900, 1714.7);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Hobart", 1357, 205556, 619.5);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Sydney", 2058, 4336374, 1214.8);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Melbourne", 1566, 3806092, 646.9);
INSERT INTO Cities(Name, Area, Population, Rainfall) VALUES("Perth", 5386, 1554769, 869.4);
This is an SQL script that creates a Cities table in the SQLite
database and fills it with seven rows. SQL is the language used to query
relational databases. The script drops any old table first, so it can be run
repeatedly. We run it with the sqlite3 command line tool against
data.db, which creates the file if it does not exist; the
command is shown at the beginning of the output below.
import sqlite3 as lite
from prettytable import from_db_cursor
con = lite.connect('data.db')
with con:
cur = con.cursor()
cur.execute('SELECT * FROM Cities')
x = from_db_cursor(cur)
print(x)
In the code example, we connect to the data.db database with the
sqlite3 module from the standard library, and select all data from
the Cities table. We generate a PrettyTable from the cursor using
the from_db_cursor method. The Id column is the
primary key, so it appears as the first column of the table.
The table has five columns, one for each column of the SQL table, including
Id.
$ sqlite3 data.db < cities.sql $ python read_from_cursor.py +----+-----------+------+------------+----------+ | Id | Name | Area | Population | Rainfall | +----+-----------+------+------------+----------+ | 1 | Adelaide | 1295 | 1158259 | 600.5 | | 2 | Brisbane | 5905 | 1857594 | 1146.4 | | 3 | Darwin | 112 | 120900 | 1714.7 | | 4 | Hobart | 1357 | 205556 | 619.5 | | 5 | Sydney | 2058 | 4336374 | 1214.8 | | 6 | Melbourne | 1566 | 3806092 | 646.9 | | 7 | Perth | 5386 | 1554769 | 869.4 | +----+-----------+------+------------+----------+
PrettyTable generation from HTML
The from_html function generates a list of PrettyTables from a
string of HTML code. HTML (HyperText Markup Language) is the language of web
pages. Each <table> element in the HTML becomes one
PrettyTable object. The from_html_one function generates a single
PrettyTable from a string of HTML that contains only one
<table>.
<html>
<body>
<table>
<tr>
<th>City name</th>
<th>Area</th>
<th>Population</th>
<th>Annual Rainfall</th>
</tr>
<tr>
<td>Adelaide</td>
<td>1295</td>
<td>1158259</td>
<td>600.5</td>
</tr>
<tr>
<td>Brisbane</td>
<td>5905</td>
<td>1857594</td>
<td>1146.4</td>
</tr>
<tr>
<td>Darwin</td>
<td>112</td>
<td>120900</td>
<td>1714.7</td>
</tr>
<tr>
<td>Hobart</td>
<td>1357</td>
<td>205556</td>
<td>619.5</td>
</tr>
<tr>
<td>Sydney</td>
<td>2058</td>
<td>4336374</td>
<td>1214.8</td>
</tr>
<tr>
<td>Melbourne</td>
<td>1566</td>
<td>3806092</td>
<td>646.9</td>
</tr>
<tr>
<td>Perth</td>
<td>5386</td>
<td>1554769</td>
<td>869.4</td>
</tr>
</table>
</body>
</html>
In the example, we use this HTML file. The first <tr> row
uses <th> header cells, which become the column names. The
other rows use <td> data cells.
from prettytable import from_html_one
with open("data.html", "r") as fp:
html = fp.read()
x = from_html_one(html)
print(x)
The example reads the whole file into a string and generates a PrettyTable with
the from_html_one function. We use from_html_one
because the file contains exactly one table.
$ python read_from_html.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+
Sorting data
With the sortby property, we specify which column is going to be
sorted. The reversesort property controls the direction of
sorting: False sorts ascending (smallest first), and
True sorts descending (largest first).
from prettytable import PrettyTable
x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
x.add_row(["Adelaide", 1295, 1158259, 600.5])
x.add_row(["Brisbane", 5905, 1857594, 1146.4])
x.add_row(["Darwin", 112, 120900, 1714.7])
x.add_row(["Hobart", 1357, 205556, 619.5])
x.add_row(["Sydney", 2058, 4336374, 1214.8])
x.add_row(["Melbourne", 1566, 3806092, 646.9])
x.add_row(["Perth", 5386, 1554769, 869.4])
print("Table sorted by population:")
x.sortby = "Population"
print(x)
print()
print("Table sorted by city in descending order:")
x.sortby = "City name"
x.reversesort = True
print(x)
In the example, we sort the data of the table twice, and print each result. Note that the sorting affects only the displayed output; the rows are stored in the order they were added.
print("Table sorted by population:")
x.sortby = "Population"
First, we sort the data by population in ascending order. The default
reversesort value is False, so no extra setting is
needed.
x.sortby = "City name" x.reversesort = True
Then we sort the data by city name in descending order by setting
reversesort to True.
$ python sorting.py Table sorted by population: +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Adelaide | 1295 | 1158259 | 600.5 | | Perth | 5386 | 1554769 | 869.4 | | Brisbane | 5905 | 1857594 | 1146.4 | | Melbourne | 1566 | 3806092 | 646.9 | | Sydney | 2058 | 4336374 | 1214.8 | +-----------+------+------------+-----------------+ Table sorted by city in descending order: +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Sydney | 2058 | 4336374 | 1214.8 | | Perth | 5386 | 1554769 | 869.4 | | Melbourne | 1566 | 3806092 | 646.9 | | Hobart | 1357 | 205556 | 619.5 | | Darwin | 112 | 120900 | 1714.7 | | Brisbane | 5905 | 1857594 | 1146.4 | | Adelaide | 1295 | 1158259 | 600.5 | +-----------+------+------------+-----------------+
Data alignment
The align property controls the alignment of the fields in each
column. Its possible values are l (left), c
(center), and r (right). Alignment is set per column by using the
column name as the key.
from prettytable import PrettyTable x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.align["City name"] = "l" x.align["Area"] = "r" x.align["Annual Rainfall"] = "r" x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x)
The code example aligns the data in the table columns. The columns that are not set keep the default centered alignment.
x.align["City name"] = "l"
We align the fields in the "City name" column to the left.
x.align["Area"] = "r" x.align["Annual Rainfall"] = "r"
We align the fields in the "Area" and "Annual Rainfall" columns to the right. Right alignment is common for numbers, because the digits line up by their place value.
$ python alignment.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+
Table styles
The set_style method changes the border characters of the table.
It takes a value from the TableStyle class. Styles change only how
the table is drawn; the data stays the same.
from prettytable import PrettyTable, TableStyle x = PrettyTable(["City name", "Population"]) x.add_row(["Adelaide", 1158259]) x.add_row(["Perth", 1554769]) x.set_style(TableStyle.DOUBLE_BORDER) print(x) x.set_style(TableStyle.MARKDOWN) print(x)
The example prints the same two-column table in two styles. The
DOUBLE_BORDER style uses double-line box characters, and the
MARKDOWN style produces a table that can be pasted into Markdown
documents.
$ python styles.py ╔═══════════╦════════════╗ ║ City name ║ Population ║ ╠═══════════╬════════════╣ ║ Adelaide ║ 1158259 ║ ║ Perth ║ 1554769 ║ ╚═══════════╩════════════╝ | City name | Population | | :-------: | :--------: | | Adelaide | 1158259 | | Perth | 1554769 |
Number formatting
The float_format property sets how floating-point numbers are
shown in a column. A floating-point number is a number with a decimal point,
such as 3.5. The value is a format string, where
.2 means two digits after the decimal point.
from prettytable import PrettyTable x = PrettyTable(["Item", "Price"]) x.add_row(["Tea", 3.5]) x.add_row(["Coffee", 12.25]) x.float_format["Price"] = ".2" print(x)
The example sets the format of the "Price" column to two decimal places. The
value 3.5 is printed as 3.50, so all prices in the
column have the same number of decimals.
$ python float_format.py +--------+-------+ | Item | Price | +--------+-------+ | Tea | 3.50 | | Coffee | 12.25 | +--------+-------+
CSV and JSON output
The get_csv_string method returns the table as CSV text, and the
get_json_string method returns it as a JSON document. JSON
(JavaScript Object Notation) is a text format for structured data that many
programs and web services can read.
from prettytable import PrettyTable x = PrettyTable(["City name", "Population"]) x.add_row(["Adelaide", 1158259]) x.add_row(["Perth", 1554769]) print(x.get_csv_string()) print(x.get_json_string())
The example prints the table once as CSV and once as JSON. The CSV output has one line per row, with the header first. The JSON output is a list whose first item is the header and whose other items are objects keyed by column name.
$ python json_csv.py
City name,Population
Adelaide,1158259
Perth,1554769
[
[
"City name",
"Population"
],
{
"City name": "Adelaide",
"Population": 1158259
},
{
"City name": "Perth",
"Population": 1554769
}
]
HTML output
The get_html_string method generates HTML output from a
PrettyTable. The result is a string of HTML <table> markup
that can be placed in a web page.
from prettytable import PrettyTable x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x.get_html_string())
The example prints the data as an HTML table. The header cells are written as
<th> elements and the data cells as <td>
elements, which is the inverse of the input file used in the HTML reading
example above.
$ python html_output.py
<table>
<thead>
<tr>
<th>City name</th>
<th>Area</th>
<th>Population</th>
<th>Annual Rainfall</th>
</tr>
</thead>
<tbody>
<tr>
<td>Adelaide</td>
<td>1295</td>
<td>1158259</td>
<td>600.5</td>
</tr>
<tr>
<td>Brisbane</td>
<td>5905</td>
<td>1857594</td>
<td>1146.4</td>
</tr>
<tr>
<td>Darwin</td>
<td>112</td>
<td>120900</td>
<td>1714.7</td>
</tr>
<tr>
<td>Hobart</td>
<td>1357</td>
<td>205556</td>
<td>619.5</td>
</tr>
<tr>
<td>Sydney</td>
<td>2058</td>
<td>4336374</td>
<td>1214.8</td>
</tr>
<tr>
<td>Melbourne</td>
<td>1566</td>
<td>3806092</td>
<td>646.9</td>
</tr>
<tr>
<td>Perth</td>
<td>5386</td>
<td>1554769</td>
<td>869.4</td>
</tr>
</tbody>
</table>
The get_string method
The get_string method returns the string representation of a
table in its current state, which is what print shows. It has
several options that control how the table is shown.
Showing title
With the title parameter, we can include a table title in the
output. The title is drawn in a row above the header.
from prettytable import PrettyTable x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x.get_string(title="Australian cities"))
The example creates a PrettyTable with a title. The title row spans the full width of the table.
$ python table_title.py +-------------------------------------------------+ | Australian cities | +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Adelaide | 1295 | 1158259 | 600.5 | | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | | Sydney | 2058 | 4336374 | 1214.8 | | Melbourne | 1566 | 3806092 | 646.9 | | Perth | 5386 | 1554769 | 869.4 | +-----------+------+------------+-----------------+
Selecting columns
With the fields option we can select which columns are going to be
displayed. The columns are shown in the order given in the list.
from prettytable import PrettyTable x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x.get_string(fields=["City name", "Population"]))
In the example, we display only the "City name" and "Population" columns. The data in the other columns is kept in the table but is not printed.
$ python select_columns.py +-----------+------------+ | City name | Population | +-----------+------------+ | Adelaide | 1158259 | | Brisbane | 1857594 | | Darwin | 120900 | | Hobart | 205556 | | Sydney | 4336374 | | Melbourne | 3806092 | | Perth | 1554769 | +-----------+------------+
Selecting rows
With the start and end parameters, we can select which
rows to display in the output. Both are zero-based indexes, and end
is exclusive, so rows from start up to but not including
end are printed.
from prettytable import PrettyTable x = PrettyTable(["City name", "Area", "Population", "Annual Rainfall"]) x.add_row(["Adelaide", 1295, 1158259, 600.5]) x.add_row(["Brisbane", 5905, 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) print(x.get_string(start=1, end=4))
In the example, we include three rows in the output: indexes 1, 2, and 3, which are Brisbane, Darwin, and Hobart.
$ python select_rows.py +-----------+------+------------+-----------------+ | City name | Area | Population | Annual Rainfall | +-----------+------+------------+-----------------+ | Brisbane | 5905 | 1857594 | 1146.4 | | Darwin | 112 | 120900 | 1714.7 | | Hobart | 1357 | 205556 | 619.5 | +-----------+------+------------+-----------------+
Handling errors
PrettyTable reports misuse with exceptions. An exception is an error signal
that stops normal execution unless the code catches it. A ValueError
is raised when a value has the wrong type or count, and an
IndexError is raised when an index is outside the table. The
example catches both with try and except.
from prettytable import PrettyTable
x = PrettyTable(["City name", "Population"])
x.add_row(["Adelaide", 1158259])
try:
x.add_row(["Perth", 1554769, 5])
except ValueError as e:
print("ValueError:", e)
try:
x.del_row(5)
except IndexError as e:
print("IndexError:", e)
The first call adds a row with three values to a two-column table, which
raises ValueError. The second call deletes row number 5, but the
table has only one row, which raises IndexError. The
try block contains the code that may fail, and the
except block runs only when that error occurs.
$ python errors.py ValueError: Row has incorrect number of values, (actual) 3!=2 (expected) IndexError: Can't delete row at index 5, table only has 1 rows
Displaying BTC tickers
In the last example, we display live BTC prices in a table. We fetch the data
from the Binance exchange with the ccxt library, which provides
a unified API to many cryptocurrency exchanges; it is installed with
pip install ccxt. Public market data does not require an API
key. See the Python ccxt article for more about
the library.
from datetime import datetime, timezone
import ccxt
from prettytable import PrettyTable
exchange = ccxt.binance()
candles = exchange.fetch_ohlcv('BTC/USDT', timeframe='1d', limit=7)
x = PrettyTable()
x.field_names = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume']
x.align = 'r'
x.float_format = '.2'
for timestamp, open_, high, low, close, volume in candles:
d = datetime.fromtimestamp(timestamp / 1000, tz=timezone.utc)
x.add_row([f'{d:%Y-%m-%d}', open_, high, low, close, volume])
print(x.get_string(title='BTC/USDT daily candles (Binance)'))
The example downloads the daily candles of the last seven days and prints them in a table. An OHLCV candle describes one time period of trading: the Open, High, Low, and Close prices, and the traded Volume.
exchange = ccxt.binance()
candles = exchange.fetch_ohlcv('BTC/USDT', timeframe='1d', limit=7)
The fetch_ohlcv method returns a list of candles for the
BTC/USDT market. Each candle is a list of six values: the start
of the period as a timestamp in milliseconds, the four prices, and the volume
in bitcoins. The limit parameter gives the number of candles,
the most recent last.
x.align = 'r' x.float_format = '.2'
Assigning a single value to align and float_format
applies it to all columns. The numbers are right-aligned and shown with two
decimal places, so the decimal points line up. We add the floats to the table
as they are and let PrettyTable format them.
d = datetime.fromtimestamp(timestamp / 1000, tz=timezone.utc)
We divide the timestamp by 1000 to get seconds and convert it to a UTC date. Daily candles on Binance start at midnight UTC.
The data is live, so the output changes with every run. The last candle is the current day, which is not finished yet; that is why its volume is small.
$ python btc_ohlcv.py +-------------------------------------------------------------------+ | BTC/USDT daily candles (Binance) | +------------+----------+----------+----------+----------+----------+ | Date | Open | High | Low | Close | Volume | +------------+----------+----------+----------+----------+----------+ | 2026-11-12 | 74015.20 | 74217.49 | 71113.06 | 71460.00 | 15228.24 | | 2026-11-13 | 71460.00 | 71514.01 | 67568.00 | 68314.00 | 29648.75 | | 2026-11-14 | 68314.01 | 68446.21 | 63320.00 | 64150.00 | 32674.75 | | 2026-11-15 | 64150.01 | 66132.01 | 62006.00 | 65351.05 | 29231.16 | | 2026-11-16 | 65351.05 | 65696.16 | 63905.01 | 64882.87 | 21929.24 | | 2026-11-17 | 64882.88 | 65447.00 | 63336.00 | 64947.35 | 28316.76 | | 2026-11-18 | 64947.36 | 65002.00 | 64136.00 | 64834.01 | 4526.27 | +------------+----------+----------+----------+----------+----------+
Source
Python prettytable GitHub page
In this article we have used the PrettyTable library to generate ASCII tables in Python. We created tables by rows and columns, read them from CSV, HTML, and a database cursor, sorted, aligned, styled, and exported them. For the text formatting of values without a table, see Python tutorials.
Author
List all Python tutorials.