Home>Article>Backend Development> How to output a table in python
You can use PrettyTable, which is a third-party library in python that can be used to generate beautiful tables in ASCII format:
PrettyTable installation(Recommended learning:Python video tutorial)
pip install prettytable
Example
import prettytable as pt # tb = pt.PrettyTable( ["City name", "Area", "Population", "Annual Rainfall"]) tb = pt.PrettyTable() tb.field_names = ["City name", "Area", "Population", "Annual Rainfall"] tb.add_row(["Adelaide",1295, 1158259, 600.5]) tb.add_row(["Brisbane",5905, 1857594, 1146.4]) tb.add_row(["Darwin", 112, 120900, 1714.7]) tb.add_row(["Hobart", 1357, 205556,619.5]) print(tb)
Output:
+-----------+------+------------+-----------------+ | 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 | +-----------+------+------------+-----------------+
If no header is added, the default Field number will be displayed, for example:
+---------+----------+----------+------------+ | Field 1 | Field 2 | Field 3 | Field 4 | +---------+----------+----------+------------+
For more Python-related technical articles, please visit thePython Tutorialcolumn. study!
The above is the detailed content of How to output a table in python. For more information, please follow other related articles on the PHP Chinese website!