The Ultimate Guide to Tabulate for Python Developers

Tabulate is a popular Python library used for creating simple ASCII tables. Its simplicity and flexibility make it a valuable tool for developers who need to present their data in an organized and readable manner. Below, you’ll find dozens of useful API explanations and code snippets to help you get started with Tabulate.

Installation

 pip install tabulate 

Basic Usage

To create a table, you can use the following simple example:

  from tabulate import tabulate
data = [["Name", "Age", "City"],
        ["Alice", 24, "New York"],
        ["Bob", 27, "Los Angeles"],
        ["Charlie", 22, "Chicago"]]

print(tabulate(data, headers="firstrow", tablefmt="grid"))  

Table Formats

The table format can be customized using the tablefmt parameter. Here are some examples:

  table = [["Sun", 696000, 1989100000],
         ["Earth", 6371, 5973.6],
         ["Moon", 1737, 73.5]]

# Plain text table print(tabulate(table, headers=["Name", "Radius (km)", "Mass (10^24 kg)"], tablefmt="plain"))
# Fancy grid table print(tabulate(table, headers=["Name", "Radius (km)", "Mass (10^24 kg)"], tablefmt="fancy_grid"))
# Pipe format table print(tabulate(table, headers=["Name", "Radius (km)", "Mass (10^24 kg)"], tablefmt="pipe"))  

String Alignment

Data cell alignment within columns can be controlled by using the colalign parameter.

  table = [["Element", "Symbol", "Atomic Number", "Mass"],
         ["Hydrogen", "H", 1, 1.008],
         ["Carbon", "C", 6, 12.011],
         ["Nitrogen", "N", 7, 14.007]]

print(tabulate(table, headers="firstrow", colalign=("left", "center", "right", "decimal"), tablefmt="grid"))  

Application Example

Consider an application that displays user data in a tabulated form:

  from flask import Flask, render_template_string from tabulate import tabulate
app = Flask(__name__)
@app.route('/') def index():
    data = [
        ['John Doe', 30, 'Software Engineer'],
        ['Jane Smith', 28, 'Data Scientist'],
        ['Emily Davis', 34, 'Product Manager']
    ]
    table = tabulate(data, headers=['Name', 'Age', 'Occupation'], tablefmt='html')
    return render_template_string('{{ table|safe }}', table=table)

if __name__ == '__main__':
    app.run(debug=True)
 

In this example, a Flask application is used to display user information in an HTML table format by utilizing the Tabulate library.

Hash: b0487a1e16081a6ae2474455558300562e133ec7310db8d389b744c6008d4f5e

Leave a Reply

Your email address will not be published. Required fields are marked *