The PrettyTable Module in Python

The PrettyTable module for Python provides a simple and effective way to display tabular data, making data analysis more accessible and convenient. Let's explore how to install PrettyTable and look at how to use this module with practical examples.

Installing PrettyTable

  1. Linux Mint

    To install PrettyTable on Linux Mint, you will need Python and the pip package manager. If they are not already installed, you can install them using the following commands:

    1sudo apt update
    2sudo apt install python3 python3-pip

    After installing Python and pip, install PrettyTable using pip:

    1pip3 install prettytable
  2. Fedora

    On Fedora, the process is similar. Make sure you have Python and pip installed:

    1sudo dnf install python3 python3-pip

    Then install PrettyTable:

    1pip3 install prettytable

Examples of Using PrettyTable

  1. Creating a Simple Table

    Let's start by creating a simple table with data:

     1from prettytable import PrettyTable
     3table = PrettyTable()
     4table.field_names = ["Name", "City", "Age"]
     6table.add_row(["Alexey", "Moscow", 30])
     7table.add_row(["Marina", "Saint Petersburg", 28])
     8table.add_row(["Igor", "Novosibirsk", 22])

    This code will create a table with three columns and three rows, where each row contains data about different people.

  2. Changing the Appearance of the Table

    PrettyTable allows you to customize the appearance of tables, including text alignment:

    1table.align["Name"] = "l"  # Align name to the left
    2table.align["City"] = "l"  # Also align city to the left
    3table.align["Age"] = "r"  # Align age to the right
  3. Adding Borders and Changing Style

    You can change the style of the borders and header of the table:

    2table.header_style = "title"

    For more examples, you can visit the official GitHub page of the module

    PrettyTable github page

Conclusion PrettyTable is an excellent tool for anyone working with data in Python. It is easy to use, customizable, and can significantly improve the readability of your data.

comments powered by Disqus