Print data sequentially in Python and output as formatted tables
I’m working on Python packages that provide an easy way to make formatted “beautiful” tables into text output. This answer provides a few suggestions.
To illustrate, the output of tabulate fits perfectly into my application:
from tabulate import tabulate
some_data = [['08:01', 1.00, 32], ['08:02', 1.01, 33], ['08:03', 1.02, 33]]
headers = ['Time', 'x', 'n']
print(tabulate(some_data, headers=headers, tablefmt='plain'))
Output:
Time x n
08:01 1 32
08:02 1.01 33
08:03 1.02 33
But I don’t want to do everything at once:
1. Print the title
2. Print the first row of data
3. Print the next one
4. … etc
Of course, I tried this :
print(tabulate(some_data[0:1], tablefmt='plain'))
Output:
08:01 1 32
This obviously won’t work perfectly, as each line will be formatted differently every time. So I need a package where you can first set up the table (specify the desired format, column width, etc.). Then output one row of data at a time.
Does anyone know if this can be implemented in one of these packages or another package that I can import?
Solution
Just by using the built-in python format
command, you get a pretty decent simple table. You can specify a format string, then use it as “template” and pass in the data to be applied to the template.
format_string = "{:<10}{:<8}{:<10}"
print(format_string.format(*headers))
for entry in some_data:
print(format_string.format(*entry))
For a complete list of various options such as padding, see https://pyformat.info