or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-tabulate

Pretty-print tabular data in Python with extensive formatting options and output format support.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/tabulate@0.9.x

To install, run

npx @tessl/cli install tessl/pypi-tabulate@0.9.0

index.mddocs/

Tabulate

A 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.

Package Information

  • Package Name: tabulate
  • Language: Python
  • Installation: pip install tabulate
  • Optional Dependencies: wcwidth for wide character (CJK) support

Core Imports

from tabulate import tabulate

Import specific utilities:

from tabulate import tabulate, tabulate_formats, simple_separated_format

Import constants for advanced usage:

from tabulate import SEPARATING_LINE, MIN_PADDING, PRESERVE_WHITESPACE, WIDE_CHARS_MODE

Import data structures for custom formatting:

from tabulate import Line, DataRow, TableFormat

Basic Usage

from 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"))

Architecture

Tabulate uses a flexible formatting system built around these core components:

  • TableFormat: Named tuple defining complete table structure (lines, rows, padding)
  • Line: Named tuple for horizontal line formatting (begin, hline, sep, end)
  • DataRow: Named tuple for row formatting (begin, sep, end)
  • Format Registry: Dictionary mapping format names to TableFormat specifications

This design enables extensible formatting through custom TableFormat objects while providing many built-in formats for common output targets.

Capabilities

Main Tabulation Function

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
    """

Format Utilities

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
    """

Constants and Configuration

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: bool

Data Structures

Core 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 present

Supported Input Data Types

Tabulate accepts various tabular data formats:

  1. List of lists - [[row1_col1, row1_col2], [row2_col1, row2_col2]]
  2. List of dictionaries - [{"col1": val1, "col2": val2}, ...] (dict keys as columns)
  3. Dictionary of iterables - {"col1": [val1, val2], "col2": [val3, val4]} (dict keys as columns)
  4. List of dataclasses - Python 3.7+ (field names as columns)
  5. Two-dimensional NumPy arrays
  6. NumPy record arrays - (record names as columns)
  7. pandas DataFrame

Supported Output Formats

Available formats accessible via tabulate_formats:

  • Plain text: "plain", "simple"
  • Grid formats: "grid", "fancy_grid", "rounded_grid", "simple_grid", "double_grid", "heavy_grid", "mixed_grid"
  • Outline formats: "outline", "fancy_outline", "rounded_outline", "simple_outline", "double_outline", "heavy_outline", "mixed_outline"
  • Markup: "pipe" (Markdown), "github" (GitHub-flavored Markdown), "html", "unsafehtml"
  • LaTeX: "latex", "latex_raw", "latex_booktabs", "latex_longtable"
  • Wiki/Documentation: "mediawiki", "moinmoin", "rst", "textile", "asciidoc"
  • Development: "orgtbl" (Org-mode), "jira", "presto", "psql", "youtrack", "pretty"
  • Data: "tsv" (tab-separated)

Command Line Interface

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.html

Available 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 specification

Advanced Usage Examples

Custom Formatting

from 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
)

Working with Different Data Sources

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"))

Separating Lines and Row Indices

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 indices

Error Handling

Common exceptions that may be raised:

  • ValueError: Raised when tabular data format is invalid, when index length doesn't match row count, or when headers format is incompatible with data type
  • ImportError: Optional dependencies (wcwidth) not available - gracefully handled internally
  • TypeError/UnicodeDecodeError: Data conversion issues - handled internally with fallbacks