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:
1 |
pip install PrettyTable |
Step 2: Import the Required Library
After successful installation, the next step is to import the PrettyTable library into your Python program.
1 |
from prettytable import PrettyTable |
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”.
1 |
t = PrettyTable(['Name', 'Age', 'City']) |
Step 4: Adding Rows to the Table
Next, we add some rows of data to the table using the add_row() function.
1 2 3 |
t.add_row(['Sam', 25, 'New York']) t.add_row(['Mary', 30, 'London']) t.add_row(['John', 35, 'Sydney']) |
Step 5: Printing the Table
Finally, we can print our table simply by invoking the print function, as shown below:
1 |
print(t) |
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:
1 2 3 4 5 6 7 8 9 |
from prettytable import PrettyTable t = PrettyTable(['Name', 'Age', 'City']) t.add_row(['Sam', 25, 'New York']) t.add_row(['Mary', 30, 'London']) t.add_row(['John', 35, 'Sydney']) print(t) |
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!