可以使用PrettyTable 是python中的一個第三方函式庫,可用來產生美觀的ASCII格式的表格:
PrettyTable安裝(推薦學習:Python影片教學)
pip install prettytable
範例
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)
輸出:
+-----------+------+------------+-----------------+ | 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 | +-----------+------+------------+-----------------+
如果沒有新增表頭,那麼會以預設的Field 編號顯示,例如:
+---------+----------+----------+------------+ | Field 1 | Field 2 | Field 3 | Field 4 | +---------+----------+----------+------------+
更多Python相關技術文章,請造訪Python教學欄位進行學習!
以上是怎麼輸出表格的詳細內容。更多資訊請關注PHP中文網其他相關文章!