How To Print A Table In Python

Python is a versatile and easy-to-understand language that is quite popular for data analysis. Therefore, understanding how to print a table in Python can be incredibly beneficial in representing and analyzing data efficiently. In this tutorial, we will learn how to create and print a table in Python using simple and straightforward steps.

Step 1: Installing the Necessary Packages

To print a table in Python, we will need to install a package called PrettyTable. If you don’t have it installed in your system, simply install it with the help of pip, which is Python’s package installer. Open your terminal or command prompt and type the following code:

Step 2: Import the Required Library

After successful installation, the next step is to import the PrettyTable library into your Python program.

Step 3: Creating the Table

Let’s create an instance of the PrettyTable and define the column names. For demonstration, we create a simple table with three columns: “Name”, “Age” and “City”.

Step 4: Adding Rows to the Table

Next, we add some rows of data to the table using the add_row() function.

Step 5: Printing the Table

Finally, we can print our table simply by invoking the print function, as shown below:

You should see the resulting table displayed like this:

+------+-----+---------+
| Name | Age |  City   |
+------+-----+---------+
| Sam  |  25 | New York|
| Mary |  30 | London  |
| John |  35 |  Sydney |
+------+-----+---------+

Full Code

Here is the complete Python code we have used in this tutorial. Feel free to copy it and try it out:

Conclusion

In conclusion, this tutorial has shown you a simple and effective way of creating and printing tables in Python using the PrettyTable library. This skill is beneficial for presenting data in a structured and readable format. Happy coding!