A simple Python library for easily displaying tabular data in a visually appealing ASCII table format
—
Core functionality for creating, manipulating, and managing table data. This includes table initialization, row and column operations, data management, and basic table structure operations.
Required imports for type annotations:
from typing import Any
from collections.abc import SequenceCreate new table instances with optional field names and formatting parameters.
class PrettyTable:
def __init__(self, field_names: Sequence[str] | None = None, **kwargs):
"""
Initialize a new PrettyTable.
Parameters:
- field_names: Sequence of column headers
- **kwargs: Formatting options (align, valign, padding_width, etc.)
"""Usage example:
# Create empty table
table = PrettyTable()
# Create table with field names
table = PrettyTable(["Name", "Age", "City"])
# Create with formatting options
table = PrettyTable(field_names=["Item", "Price"], padding_width=2, align="l")Add, remove, and manage table rows with support for dividers and bulk operations.
def add_row(self, row: list[Any], *, divider: bool = False) -> None:
"""
Add a single row to the table.
Parameters:
- row: List of values for each column
- divider: Whether to add a divider after this row
"""
def add_rows(self, rows: list[list[Any]], *, divider: bool = False) -> None:
"""
Add multiple rows to the table.
Parameters:
- rows: List of row lists
- divider: Whether to add dividers after each row
"""
def del_row(self, row_index: int) -> None:
"""
Delete a row by index.
Parameters:
- row_index: Zero-based index of row to delete
"""
def add_divider(self) -> None:
"""Add a divider after the last row."""Usage examples:
# Add single row
table.add_row(["Alice", 25, "New York"])
# Add row with divider
table.add_row(["Bob", 30, "Boston"], divider=True)
# Add multiple rows
table.add_rows([
["Charlie", 35, "Chicago"],
["Diana", 28, "Denver"]
])
# Delete second row
table.del_row(1)
# Add divider
table.add_divider()Add, remove, and manage table columns with alignment options.
def add_column(self, fieldname: str, column: list[Any], align: str = 'c', valign: str = 't') -> None:
"""
Add a new column to the table.
Parameters:
- fieldname: Name for the column header
- column: List of values for the column
- align: Column alignment ('l', 'c', 'r')
- valign: Vertical alignment ('t', 'm', 'b')
"""
def del_column(self, fieldname: str) -> None:
"""
Delete a column by field name.
Parameters:
- fieldname: Name of column to delete
"""
def add_autoindex(self, fieldname: str = 'Index') -> None:
"""
Add an auto-incrementing index column.
Parameters:
- fieldname: Name for the index column
"""Usage examples:
# Add column with data
table.add_column("Score", [95, 87, 92, 78], align='r')
# Add auto-incrementing index
table.add_autoindex()
# Delete column
table.del_column("Score")Clear, copy, and manage table data while preserving or modifying structure.
def clear_rows(self) -> None:
"""Remove all rows but keep field names and formatting."""
def clear(self) -> None:
"""Remove all data including field names and reset formatting."""
def copy(self) -> 'PrettyTable':
"""Create a deep copy of the table."""Usage examples:
# Clear all rows but keep headers
table.clear_rows()
# Clear everything
table.clear()
# Create a copy
table_copy = table.copy()Access and modify table structure and data through properties.
@property
def field_names(self) -> list[str]:
"""Get or set column headers."""
@field_names.setter
def field_names(self, value: list[str]) -> None: ...
@property
def rows(self) -> list[list[Any]]:
"""Get all data rows."""
@property
def dividers(self) -> list[bool]:
"""Get divider positions."""Usage examples:
# Set field names
table.field_names = ["Name", "Age", "City"]
# Get field names
headers = table.field_names
# Access all rows
all_data = table.rows
# Check divider positions
divider_list = table.dividersControl table appearance through formatting properties.
@property
def align(self) -> dict[str, str]:
"""Column alignment settings."""
@property
def valign(self) -> dict[str, str]:
"""Vertical alignment settings."""
@property
def title(self) -> str | None:
"""Table title."""
@title.setter
def title(self, value: str | None) -> None: ...
@property
def header(self) -> bool:
"""Whether to show header row."""
@header.setter
def header(self, value: bool) -> None: ...
@property
def border(self) -> bool:
"""Whether to show table border."""
@border.setter
def border(self, value: bool) -> None: ...Usage examples:
# Set column alignment
table.align["Name"] = "l"
table.align["Age"] = "r"
# Set table title
table.title = "Employee Data"
# Control header display
table.header = True
# Control border display
table.border = FalseApply predefined styles and manage formatting options.
def set_style(self, style: TableStyle) -> None:
"""
Apply a predefined table style.
Parameters:
- style: TableStyle enum value
"""Usage example:
from prettytable import TableStyle
# Apply markdown style
table.set_style(TableStyle.MARKDOWN)
# Apply double border style
table.set_style(TableStyle.DOUBLE_BORDER)Access dynamic table information and advanced formatting properties.
@property
def rowcount(self) -> int:
"""Number of data rows in the table (read-only)."""
@property
def colcount(self) -> int:
"""Number of columns in the table (read-only)."""
@property
def none_format(self) -> dict[str, str]:
"""Format string for None values in each column."""
@none_format.setter
def none_format(self, value: dict[str, str]) -> None: ...
@property
def preserve_internal_border(self) -> bool:
"""Whether to preserve internal borders when printing without header."""
@preserve_internal_border.setter
def preserve_internal_border(self, value: bool) -> None: ...
@property
def print_empty(self) -> bool:
"""Whether to print table when empty."""
@print_empty.setter
def print_empty(self, value: bool) -> None: ...Usage examples:
# Check table dimensions
print(f"Table has {table.rowcount} rows and {table.colcount} columns")
# Set None value formatting
table.none_format["Score"] = "N/A"
table.none_format["Name"] = "-"
# Control empty table printing
table.print_empty = False
# Control internal borders
table.preserve_internal_border = TrueSupport for advanced table operations and integrations.
def __getitem__(self, index: slice | int) -> 'PrettyTable':
"""
Slice table rows to create new table.
Parameters:
- index: Slice object or integer for row selection
Returns:
New PrettyTable containing selected rows
"""
def _repr_html_(self) -> str:
"""HTML representation for Jupyter notebook display."""Usage examples:
# Slice table (first 5 rows)
first_five = table[:5]
# Get specific row as single-row table
row_table = table[2]
# Slice with step
every_other = table[::2]
# Jupyter notebook will automatically use _repr_html_
# when displaying table in cells
table # Displays as HTML table in JupyterExtended output formatting capabilities.
def get_formatted_string(self, out_format: str, **kwargs) -> str:
"""
Get table string in specified format.
Parameters:
- out_format: Output format ("csv", "json", "html", "latex", "mediawiki")
- **kwargs: Format-specific options
Returns:
Formatted table string
"""Usage example:
# Get formatted output
csv_output = table.get_formatted_string("csv")
json_output = table.get_formatted_string("json")
html_output = table.get_formatted_string("html", attributes={"class": "my-table"})Install with Tessl CLI
npx tessl i tessl/pypi-prettytable