Home  >  Article  >  Backend Development  >  How to output a table in python

How to output a table in python

(*-*)浩
(*-*)浩Original
2019-07-03 13:52:139587browse

You can use PrettyTable, which is a third-party library in python that can be used to generate beautiful tables in ASCII format:

How to output a table in python

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 the Python Tutorial column. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to align in pythonNext article:How to align in python