How to Print a Table in Python
Python has no built-in print.table function, but you can print a table by looping through rows and formatting each cell to a consistent width. For a multiplication table from 1 through 10, use range(1, 11) because Python stops a range() just before its ending value. Start with built-in formatting for simple terminal output, then use a library or DataFrame display when you need headers, borders, CSV input, or notebook rendering.
What Printing a Table Means in Python
print() writes text representations of values to standard output, usually your terminal or notebook cell output. A “table” is not a special Python type: it is formatted text arranged in rows and columns.
The essential parts are:
- A sequence of rows, often a list of tuples or lists
- One consistent format for every row
- Column widths and alignment rules
- A loop that prints each row
A formatted table works best when you control the values. If the data comes from a CSV file, database, or DataFrame, parse or structure it first instead of trying to align raw text.
Choose a table-printing approach based on the data source and the output you need:
| Situation | Best Approach | Why |
|---|---|---|
| Small list of rows you create in code | f-strings or str.format() |
No dependency and full control |
| Numeric, square, cube, or multiplication output | A for loop with numeric format fields |
Keeps number columns aligned |
| Headers, borders, missing values, or many styles | tabulate |
Handles common table formatting |
| Rows read from a CSV file | csv module, then a formatter |
Correctly handles quoted fields and delimiters |
| A DataFrame in Jupyter | display(df) or a final df expression |
Produces a rich notebook table |
| Nested dictionaries or lists being debugged | pprint |
Makes structures readable, not tabular |
How to Print a Simple Python Table
With a list of tuples and one row format string, you can print aligned headers, a matching divider, and data rows; indent the print call within the row loop.
Step 1: Define the Rows and a Row Format
Create data as a list of tuples, then define one format string that controls column alignment. In format fields, < aligns left, > aligns right, and ^ centers text. The number after the alignment is the minimum field width.
rows = [
("Ada", 42, "open"),
("Lin", 7, "closed"),
("Maya", 105, "pending"),
]
row_format = "{:<10} | {:>5} | {:<8}"
This format gives names at least 10 characters of left-aligned space, scores at least 5 characters of right-aligned space, and statuses at least 8 characters of left-aligned space.
For a compact four-column row, this format string uses automatic, centered, right, and left alignment:
row_format = "| {:1} | {:^4} | {:>4} | {:<3} |"
Here, the fields reserve widths of 1, 4, 4, and 3 characters. A text value in {:1} displays naturally from the left, {:^4} centers a value, {:>4} right-aligns it, and {:<3} left-aligns it.
Step 2: Print the Header and Divider
Use a format string with a field for each heading and row value. That keeps the header aligned with the data below it.
header = row_format.format("Name", "Score", "Status")
print(header)
print("-" * len(header))
The three-column format produces a readable heading and a divider sized to match it.
Step 3: Loop Through the Rows
Unpack each row into the format string and print it. for row in rows: print(row_format.format(*row))
for row in rows:
print(row_format.format(*row))
rows = [
("Ada", 42, "open"),
("Lin", 7, "closed"),
("Maya", 105, "pending"),
]
row_format = "{:<10} | {:>5} | {:<8}"
header = row_format.format("Name", "Score", "Status")
print(header)
print("-" * len(header))
for row in rows:
print(row_format.format(*row))
The output is:
Name | Score | Status
---------------------------
Ada | 42 | open
Lin | 7 | closed
Maya | 105 | pending
Python’s string-formatting tools support both f-strings and str.format(). F-strings are often easier when values already have names; str.format() is convenient when formatting an entire row stored as a tuple or list.
Print Numeric and Multiplication Tables
Numeric columns normally look best right-aligned because digits line up by place value.
Print a Table of 7
Use an indented loop body for valid Python code. number = 7 for multiplier in range(1, 11): product = number * multiplier print(f”{number} x {multiplier:2d} = {product:2d}”)
number = 7
for multiplier in range(1, 11):
product = number * multiplier
print(f"{number} x {multiplier:2d} = {product:2d}")
The :2d fields reserve space for two-digit integers, which keeps the equals signs and products aligned.
Print Multiplication Tables From 1 Through 10
Indent each loop body.
for number in range(1, 11):
print(f"Table of {number}")
for multiplier in range(1, 11):
print(f"{number:2d} x {multiplier:2d} = {number * multiplier:3d}")
print()
The final print() adds a blank line between each multiplication table.
Print Number, Square, and Cube Columns
For a generated numeric table, fixed-width integer fields make each column line up cleanly.
print(" N Square Cube")
print("----------------")
for x in range(1, 11):
print("{0:2d} {1:3d} {2:4d}".format(x, x * x, x * x * x))
The 2d, 3d, and 4d fields reserve fixed widths for the number, square, and cube columns. This is a useful pattern when the output values have predictable numeric types.
Use Tabulate for Headers, Borders, and Missing Values
Use standard string formatting for a small generated console table whose rows you control; choose tabulate when you need configurable headers, table styles, or numeric formatting.
Install the package in the Python environment where you will run the script:
python -m pip install tabulate
I use a Python virtual environment before installing tabulate so a project’s formatting dependency does not affect unrelated projects.
This complete example creates a simple table with headers and four decimal places for floats.
from tabulate import tabulate
planets = [
["Mercury", 2439.7, 0.3301],
["Venus", 6051.8, None],
["Earth", 6371.0, 5.9722],
]
headers = ["Planet", "R (km)", "mass (x 10^29 kg)"]
print(
tabulate(
planets,
headers=headers,
tablefmt="simple",
floatfmt=".4f",
missingval="?",
)
)
Use one header for each data column, and make each header’s unit label match the values in that column. Set tablefmt="simple" for a restrained terminal style. When decimal precision matters, floatfmt=".4f" displays four digits after the decimal point, and missingval="?" makes absent cells obvious.
If you prefer a grid-style table, PrettyTable is another option. After you create the table instance and add integer values, set int_format = '8' to format its integer fields with that format setting.
python -m pip install prettytable
from prettytable import PrettyTable
table = PrettyTable()
table.field_names = ["Service", "Requests"]
table.add_row(["API", 124])
table.add_row(["Worker", 8])
table.int_format = "8"
print(table)
Print a Table From a CSV File
Do not split CSV lines with line.split(","). CSV fields can contain commas, quote characters, and alternate delimiters, so raw splitting can produce broken columns.
Open CSV files with newline='' before passing them to Python’s csv.reader. The csv module returns each parsed row as a list of strings; you can then print it directly or send it to a table formatter.
import csv
from tabulate import tabulate
with open("planets.csv", newline="", encoding="utf-8") as file:
reader = csv.reader(file)
headers = next(reader)
rows = list(reader)
print(tabulate(rows, headers=headers, tablefmt="simple"))
This reads the first CSV row as the header and all remaining rows as table data. Python’s CSV documentation specifies newline='' when opening a CSV file for use with its reader and writer objects.
If a CSV column contains numbers that must be sorted or formatted as numbers, convert it after reading. For example, float(row[1]) converts the second column of a row from text to a floating-point value before you pass it to a formatter.
Display Python Results as Tables in Notebooks
Yes, Python notebooks can display tables. A pandas DataFrame renders as an HTML table when it is the final expression in a Jupyter cell, or when you explicitly call display().
import pandas as pd
from IPython.display import display
df = pd.DataFrame(
{
"Name": ["Ada", "Lin", "Maya"],
"Score": [42, 7, 105],
"Status": ["open", "closed", "pending"],
}
)
display(df)
For terminal output instead of a rich notebook table, use to_string().
print(df.to_string(index=False))
Pandas may shorten long DataFrames during display. Before displaying a DataFrame whose row count exceeds the current display limit, set display.max_rows to df.shape[0] + 1.
pd.set_option("display.max_rows", df.shape[0] + 1)
display(df)
The extra row in that setting allows the complete DataFrame to display rather than being truncated by the normal row limit.
Check That the Printed Table Is Correct
Before relying on terminal output or copying it into logs, verify these points:
- Every data row uses the same format string as the header.
- Numeric columns use right alignment when readers need to compare digits.
- Long values do not make important columns hard to read; fixed widths are minimum widths, not truncation limits.
- CSV data is parsed with
csv.readerorcsv.DictReader, not manually split on commas. - Missing data has a deliberate representation, such as
?intabulate. - Notebook output is appropriate for people, while CSV or JSON is usually better for another program to consume.
For nested dictionaries, configuration objects, or API responses that are not truly rows and columns, use pprint.pp() instead of forcing the data into a table.
Start with the built-in formatting example for controlled data, then move to tabulate, CSV parsing, or DataFrame display when your output needs richer structure.
Frequently Asked Questions
What Is print() in Python?
print() is a built-in function that writes values to standard output. It does not create columns or borders by itself; a table appears only after you format values into aligned text, such as f"{name:<10} | {score:>5}".
Do I Need a Library to Print a Table in Python?
No. A loop plus f-strings or str.format() is enough for a small table. Use tabulate when you need features such as column headers, tablefmt="simple", floatfmt=".4f" for decimal cells, or missingval="?" for empty values.
Why Are My Python Table Columns Not Lining Up?
Columns fail to line up when rows use different formatting rules or when numbers and text have inconsistent alignment. Format every row with one shared string, such as "{:<10} | {:>5} | {:<8}", and parse CSV data with csv.reader using newline=''.
