Printing Data as Tabular Data
You encounter challenges in formatting data for tabular output in Python. You have a list of headings and a matrix containing the table data.
Specifically, you want to present the data as follows:
Solution
Python offers several options for elegantly solving this task:
1. tabulate (https://pypi.python.org/pypi/tabulate)
from tabulate import tabulate print(tabulate([['Alice', 24], ['Bob', 19]], headers=['Name', 'Age']))
Output:
Name Age ------ ----- Alice 24 Bob 19
2. PrettyTable (https://pypi.python.org/pypi/PrettyTable)
from prettytable import PrettyTable t = PrettyTable(['Name', 'Age']) t.add_row(['Alice', 24]) t.add_row(['Bob', 19]) print(t)
Output:
+-------+-----+ | Name | Age | +-------+-----+ | Alice | 24 | | Bob | 19 | +-------+-----+
3. texttable (https://pypi.python.org/pypi/texttable)
from texttable import Texttable t = Texttable() t.add_rows([['Name', 'Age'], ['Alice', 24], ['Bob', 19]]) print(t.draw())
Output:
+-------+-----+ | Name | Age | +=======+=====+ | Alice | 24 | +-------+-----+ | Bob | 19 | +-------+-----+
The above is the detailed content of How Can I Efficiently Format Data into a Tabular Output in Python?. For more information, please follow other related articles on the PHP Chinese website!