Pretty-print tabular data in Python with extensive formatting options and output format support.
npx @tessl/cli install tessl/pypi-tabulate@0.9.0A comprehensive Python library for pretty-printing tabular data with extensive formatting options and output format support. Tabulate automatically detects column types, provides intelligent alignment including decimal point alignment, and supports numerous output formats for documentation, markup, and presentation purposes.
pip install tabulatewcwidth for wide character (CJK) supportfrom tabulate import tabulateImport specific utilities:
from tabulate import tabulate, tabulate_formats, simple_separated_formatImport constants for advanced usage:
from tabulate import SEPARATING_LINE, MIN_PADDING, PRESERVE_WHITESPACE, WIDE_CHARS_MODEImport data structures for custom formatting:
from tabulate import Line, DataRow, TableFormatfrom tabulate import tabulate
# Simple table from list of lists
table = [["Sun", 696000, 1989100000],
["Earth", 6371, 5973.6],
["Moon", 1737, 73.5],
["Mars", 3390, 641.85]]
print(tabulate(table))
# Output:
# ----- ------ -------------
# Sun 696000 1.9891e+09
# Earth 6371 5973.6
# Moon 1737 73.5
# Mars 3390 641.85
# ----- ------ -------------
# Table with headers
print(tabulate(table, headers=["Planet", "R (km)", "mass (x 10^29 kg)"]))
# Output:
# Planet R (km) mass (x 10^29 kg)
# -------- -------- -------------------
# Sun 696000 1.9891e+09
# Earth 6371 5973.6
# Moon 1737 73.5
# Mars 3390 641.85
# Different output formats
print(tabulate(table, headers=["Planet", "R (km)", "mass"], tablefmt="grid"))
print(tabulate(table, headers=["Planet", "R (km)", "mass"], tablefmt="html"))
print(tabulate(table, headers=["Planet", "R (km)", "mass"], tablefmt="markdown"))Tabulate uses a flexible formatting system built around these core components:
This design enables extensible formatting through custom TableFormat objects while providing many built-in formats for common output targets.
The primary function for formatting tabular data with comprehensive options for data types, alignment, formatting, and output styles.
def tabulate(
tabular_data,
headers=(),
tablefmt="simple",
floatfmt="g",
intfmt="",
numalign="default",
stralign="default",
missingval="",
showindex="default",
disable_numparse=False,
colalign=None,
maxcolwidths=None,
rowalign=None,
maxheadercolwidths=None
):
"""
Format tabular data into a pretty-printed table.
Args:
tabular_data: Input data - list of lists, dict of iterables, pandas DataFrame,
list of dicts, list of dataclasses, NumPy arrays, etc.
headers (tuple): Column headers - list, "firstrow", "keys", or empty tuple
tablefmt (str): Output format - see tabulate_formats for options
floatfmt (str): Float formatting specification or list per column
intfmt (str): Integer formatting specification or list per column
numalign (str): Numeric alignment - "left", "right", "center", "decimal", "default"
stralign (str): String alignment - "left", "right", "center", "default"
missingval (str): Replacement for None values
showindex (str/bool): Row index display - "default", "always", "never", True, False, or iterable
disable_numparse (bool): Disable automatic number parsing
colalign (list): Per-column alignment override
maxcolwidths (list/int): Maximum column widths
rowalign (str/list): Row-wise alignment options
maxheadercolwidths (list/int): Maximum header column widths
Returns:
str: Formatted table as string
"""Access to available output formats and custom format creation.
# List of all supported output formats
tabulate_formats: list[str]
def simple_separated_format(separator):
"""
Create a custom TableFormat with columns separated by a separator.
Args:
separator (str): String separator between columns
Returns:
TableFormat: Custom format object for use with tablefmt parameter
"""Runtime constants affecting table formatting behavior.
# Special marker for separating lines in table data (unprintable character)
SEPARATING_LINE: str = "\001"
# Minimum extra space in headers
MIN_PADDING: int = 2
# Whether to preserve leading/trailing whitespace in data
PRESERVE_WHITESPACE: bool = False
# Whether wide-character (CJK) support is enabled (depends on wcwidth)
WIDE_CHARS_MODE: boolCore data structures for custom table formatting.
class Line:
"""Represents table line formatting (namedtuple)."""
begin: str # Line beginning character(s)
hline: str # Horizontal line character(s)
sep: str # Column separator character(s)
end: str # Line ending character(s)
class DataRow:
"""Represents table row formatting (namedtuple)."""
begin: str # Row beginning character(s)
sep: str # Column separator character(s)
end: str # Row ending character(s)
class TableFormat:
"""Complete table format specification (namedtuple)."""
lineabove: Line | None # Line above table
linebelowheader: Line | None # Line below header row
linebetweenrows: Line | None # Line between data rows
linebelow: Line | None # Line below table
headerrow: DataRow | None # Header row format
datarow: DataRow | None # Data row format
padding: int # Padding around cell content
with_header_hide: list | None # Elements to hide when headers presentTabulate accepts various tabular data formats:
[[row1_col1, row1_col2], [row2_col1, row2_col2]][{"col1": val1, "col2": val2}, ...] (dict keys as columns){"col1": [val1, val2], "col2": [val3, val4]} (dict keys as columns)Available formats accessible via tabulate_formats:
"plain", "simple""grid", "fancy_grid", "rounded_grid", "simple_grid", "double_grid", "heavy_grid", "mixed_grid""outline", "fancy_outline", "rounded_outline", "simple_outline", "double_outline", "heavy_outline", "mixed_outline""pipe" (Markdown), "github" (GitHub-flavored Markdown), "html", "unsafehtml""latex", "latex_raw", "latex_booktabs", "latex_longtable""mediawiki", "moinmoin", "rst", "textile", "asciidoc""orgtbl" (Org-mode), "jira", "presto", "psql", "youtrack", "pretty""tsv" (tab-separated)Tabulate includes a command-line utility for processing files:
# Basic usage
tabulate data.csv
# With options
tabulate -f grid -1 --float .2f data.csv
# From stdin
cat data.txt | tabulate -f html > output.htmlAvailable CLI options:
-h, --help: Show help message-f, --format FMT: Set output table format-1, --header: Use first row as header-o FILE, --output FILE: Output to file-s REGEXP, --sep REGEXP: Custom column separator-F FPFMT, --float FPFMT: Float number format-I INTFMT, --int INTFMT: Integer number format-C, --colalign: Column alignment specificationfrom tabulate import tabulate, simple_separated_format
# Custom separator format
tsv_format = simple_separated_format("\\t")
result = tabulate(data, tablefmt=tsv_format)
# Custom number formatting per column
result = tabulate(
data,
floatfmt=[".2f", ".4f"], # Different formats per column
intfmt=["d", "04d"] # Different int formats per column
)
# Alignment control
result = tabulate(
data,
numalign="decimal", # Align numbers by decimal point
stralign="center", # Center string columns
colalign=["left", "right", "center"] # Per-column override
)import pandas as pd
import numpy as np
# From pandas DataFrame
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
print(tabulate(df, headers="keys", tablefmt="grid"))
# From NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(tabulate(arr, headers=["X", "Y", "Z"]))
# From list of dictionaries
data = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
print(tabulate(data, headers="keys"))from tabulate import tabulate, SEPARATING_LINE
# Add separating lines between data sections
data = [
["Group A", "", ""],
["Alice", "Engineer", 75000],
["Bob", "Designer", 65000],
[SEPARATING_LINE], # Separating line
["Group B", "", ""],
["Carol", "Manager", 85000],
["Dave", "Analyst", 55000]
]
print(tabulate(data, headers=["Name", "Role", "Salary"], tablefmt="grid"))
# Show row indices
print(tabulate(data, showindex="always"))
print(tabulate(data, showindex=["Row1", "Row2", "Row3"])) # Custom indicesCommon exceptions that may be raised: