How to Create Table in Python
In this document, you will learn how to create tables in Python, how to format them, and how parsing is useful. Python provides tabulate library to create tables and format them.
To install the tabulate library execute the below command on your system:
What is Tabulate Module?
This module helps in pretty-print tabular data in Python; a library that helps in providing better command-line utility. The main usages of the module are:
- printing miniature sized tables without hassle or formatting tools. It requires only one function call, nor another formatting requirement. This module can easily understand how to frame the table.
- composing tabular data for lightweight plain-text markup: numerous output forms appropriate for additional editing or transformation
- readable presentation of diverse textual and numeric data: configurable number formatting, smart column alignment, alignment by a decimal point
It leverages a method called the tabulate() that takes a list containing n nested lists to create n rows table.
Program:
Output:
Explanation:
Here we have used the module Tabulate that takes a list of lists (also known as a nested list) and stored it under the object name table. Then we use the tabulate() method where we passed the table object (nested list). This will automatically arrange the format in a tabular fashion.
Table Headers
To get headers or column headings you can use the second argument in tabulate() method as headers. For example,
Explanation:
Here we have used the module Tabulate that takes a list of lists (also known as a nested list) and stored it under the object name table. Then we use the tabulate() method where we passed the ‘table’ object (nested list). This time we take another parameter headers that takes two string values ‘Name’ and ‘Age’ that will be the title of the columns. This will automatically arrange the format in a tabular fashion.
Output:
In the list of lists, you can assign the first list for column headers containing all column headings, and assign headers’ value as “firstrow”.
Example:
Output:
You can also pass a dictionary to tabulate() method where keys will be the column headings and assign headers’ value as “keys”.
Example:
Output:
Row Index
You can display the index column containing indexes for all rows in the table.
Example:
Output:
To hide the index column you can use showindex as ‘False’ or showindex as ‘never’ .
Example:
Output:
To have a custom index column, pass an iterable as the value of showindex argument.
Example:
Output:
Number formatting
The tabulate() method allows you to display the specific count of numbers after a decimal point in a decimal number using floatfmt argument.
Example: Adding a new column Height in the above example:
Output:
Formatting the height values up to two digits:
Output:
Table format
You can format the table in multiple ways using tablefmt argument. Following are a few of them:
- plain
- simple
- html
- jira
- psql
- github
- pretty
plain: It formats the table in a plain simple way without any outer lines:
Example:
Output:
simple: It is the default formatting in tabulate() method that displays the table with one horizontal line below the headers:
Example:
Output:
html: It displays the table in html code format:
Example:
Output:
jira: Displays the table in Atlassian Jira markup language format:
Example:
Output:
Psql: It displays the table in Postgres SQL form.
Output:
Github: It displays the table in GitHub mardown form.
Output:
Pretty: Displays table in the form followed by PrettyTables library
Output:
PrettyTable Module:
PrettyTable is another Python library that helps in creating simple ASCII tables. It got inspired by the ASCII tables generated and implemented in the PostgreSQL shell psql. This library allows controlling many aspects of a table, such as the the alignment of text, width of the column padding, or the table border. Also it allows sorting data.
Creating a Table using Python:
Creating a table in Python is very easy using the PrettyPrint library. Simply import the module and use its add_row() method to add multiple rows or create a table row-wise.
Example:
Output:
Example to create a table column-wise:
Output:
Conclusion:
Table plays a significant role in software development where the developer wants to create a formatted output. A lot of CLI-based software requires such formatting. Formatting through tabular form also helps in giving a crisp idea of the data so that the users can easily understand what the data wants to convey. Both these modules work well for representing data in tabular format. Web development using Python also requires these modules.
Как напечатать таблицу с помощью f-string
В этой статье мы разберём как напечатать красивые таблицы:
- с одинаковой шириной колонок;
- с разной шириной колонок;
- с шапкой из двух строк.
А также создадим функции:
- с параметром максимальной ширины таблицы;
- для записи таблицы в текстовый файл.
«F-строки» были введены ещё в версии Python 3.6, и все уже давно, наверно, их используют в своём коде. Для тех, кто хочет освежить память, и ещё раз перечитать документацию — PEP 498 — Literal String Interpolation. Мы же будем использовать «f-строки» для вывода данных в табличном виде. Для примера возьмём данные об автомобилях с одного из онлайн-рынков такой структуры:
Таблица с одинаковой шириной колонок
Для того, чтоб данные в колонках таблицы выровнять по центру, левому или правому краю, нужно рассчитать ширину колонок и определить отступ. Давайте сделаем ширину колонок одинаковой по максимальной строке столбца и отступом в один символ.
Функция с параметром максимальной ширины таблицы
Давайте соберём наш код в функцию, но добавим ещё один параметр — максимальную ширину таблицы. И если ширина таблицы будет больше максимальной, заданной по умалчиванию — выведем сообщение. А также сделаем выравнивание текста в строках шапки таблицы по центру, в теле таблицы — по правому краю. Для этого надо всего лишь перед значением ширины строки вставить символ «^» — выравнивание по центру, «>» — выравнивание по правому краю, «<» – выравнивание по левому краю, выставлено по умолчанию.

Давайте ещё изменим вывод нашей таблицы. Колонки «Цена $» и «Пробег км» выведем с , , как разделитель тысяч.
Здесь, в 52 строке кода, в f’

Но это ещё не все возможности «спецификации формата».
Примечание: в F-string в фигурных скобках <> помещены «заменяющие поля». Двоеточие : указывает на поле format_spec , что означает нестандартный формат замены. Для него существует Мини-язык спецификации формата.
Функция для записи таблицы в текстовый файл
Часто приходится не только печатать таблицу, но и сохранять её в текстовом файле. Имея готовую функцию для печати, нетрудно переделать её для записи.
Как вывести таблицу в питоне
In this article, we are going to discuss how to make a table in Python. Python provides vast support for libraries that can be used for creating different purposes. In this article we will talk about two such modules that can be used to create tables.
Method 1: Using Tabulate module
The tabulate() method is a method present in the tabulate module which creates a text-based table output inside the python program using any given inputs. It can be installed using the below command
Python Print Table
By
Priya Pedamkar

Introduction to Python Print Table
Python is quite a powerful language when it comes to its data science capabilities. Moreover, the Printing tables within python are sometimes challenging, as the trivial options provide you with the output in an unreadable format. We got you covered. There are multiple options to transform and print tables into many pretty and more readable formats. If you are working on python in a Unix / Linux environment, then readability can be a huge issue from the user’s perspective.
How to Print Table in Python?
There are several ways that can be utilized to print tables in python, namely:
Web development, programming languages, Software testing & others
- Using format() function to print dict and lists
- Using tabulate() function to print dict and lists
- texttable
- beautifultable
- PrettyTable
Reading data in a tabular format is much easier as compared to an unstructured format, as given below:
- Pos, Lang, Percent, Change
- 1, Python, 33.2, UP
- 2, Java, 23.54, DOWN
- 3, Ruby, 17.22, UP
- 5, Groovy, 9.22, DOWN
- 6, C, 1.55, UP
- 10, Lua, 10.55, DOWN
Tabular Format
Pos Lang Percent Change
1 Python 33.2 UP
2 Java 23.54 DOWN
3 Ruby 17.22 UP
5 Groovy 9.22 DOWN
6 C 1.55 UP
10 Lua 10.55 DOWN
How can we Print Tables in Python?
We tend to use the information from a dictionary or a list quite frequently. One way of printing the same can be:
![]()
![]()
![]()
![]()
![]()
![]()
![]()
![]()
1. Unformatted Fashion
Let us take an example to understand this in detail
Code:
Output:

The above example’s output is quite unreadable; let’s take another example of how can we print readable tables in python.
2. Formatted Fashion
Code:
Output:

- This gives us a better readability option using the format function in a print command
- What if we want to print the data from a list in a tabular format in python? How can this be done?
3. By utilizing the Format Function
Code:
Output:

4. By utilizing the Tabulate Function
Let’s have another example to understand the same in quite some detail.
Code:
Output:

The best part is, that you do not need to format each print statement every time you add a new item to the dictionary or the list. There are several other ways as well that can be utilized to print tables in python, namely:
- texttable
- beautifultable
- PrettyTable
- Otherwise, Pandas is another pretty solution if you are trying to print your data in the most optimized format.
5. Print table using pandas in detail
Pandas is a python library that provides data handling, manipulation, and a diverse range of capabilities in order to manage, alter and create meaningful metrics out of your dataset. Let’s take the below example in order to understand the print table option with pandas in detail.
Output:

How does it work?
- We imported the panda’s library using the import statement
- >> import pandas
- Thereafter declared a list of list and assigned it to the variable named “data.”
- in the very next step, we declared the headers
- >> headers=[“Pos”, “Team”, “Win”, “Lose”]
How can we print this List in a Formatted Readable Structure?
- Pandas have the power of data frames, which can handle, modify, update and enhance your data in a tabular format.
- We have utilized the data frame module of the pandas library along with the print statement to print tables in a readable format.
Conclusion
Reading data in a tabular format is much easier as compared to an unstructured format. Utilizing the capability of python print statements with numerous functions can help you attain better readability for the same.
Recommended Articles
This is a guide to Python Print Table. Here we discuss the introduction to Python Print Table, and how to print tables with different examples. You can also go through our other related articles to learn more –