### Install and Run Doctest Source: https://github.com/astanin/python-tabulate/blob/master/README.md Install pytest-doctestplus and run doctests on the README.md file. This verifies the correctness of embedded examples. ```shell python3 -m pip install pytest-doctestplus[md] ``` ```shell python3 -m doctest README.md ``` -------------------------------- ### Install tabulate library only Source: https://github.com/astanin/python-tabulate/blob/master/README.md Install only the Python library on Unix-like systems by setting an environment variable. ```shell TABULATE_INSTALL=lib-only pip install tabulate ``` -------------------------------- ### Install tabulate for current user Source: https://github.com/astanin/python-tabulate/blob/master/README.md Install the library and utility for the current user only. ```shell pip install tabulate --user ``` -------------------------------- ### Static Table Format Example Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/architecture.md Illustrates the definition of a static table format using pre-computed TableFormat objects. This example shows the 'simple' format configuration. ```python _table_formats["simple"] = TableFormat( lineabove=Line("", "-", " ", ""), linebelowheader=Line("", "-", " ", ""), # ... other fields ) ``` -------------------------------- ### Install tabulate Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/index.md Install the tabulate library using pip. For wide character support (CJK, emoji), install with the 'widechars' extra. ```bash pip install tabulate pip install "tabulate[widechars]" ``` -------------------------------- ### Install tabulate library only on Windows Source: https://github.com/astanin/python-tabulate/blob/master/README.md Install only the Python library on Windows by setting an environment variable. ```shell set TABULATE_INSTALL=lib-only pip install tabulate ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/index.md Install the tabulate library with optional dependencies for handling wide characters. This is recommended for correct alignment of CJK characters and emojis. ```bash pip install "tabulate[widechars]" ``` -------------------------------- ### Install tabulate library Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Install the tabulate library and its CLI utility using pip. Options include installing only the library, with wide character support, or the development version. ```bash # Install library and CLI utility pip install tabulate # Install library only (on Unix) TABULATE_INSTALL=lib-only pip install tabulate # Install with wide character support for CJK pip install "tabulate[widechars]" # Install development version pip install tabulate[widechars] ``` -------------------------------- ### Dynamic Table Format Example with Callables Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/architecture.md Shows how dynamic table formats use functions to compute formatting. This example demonstrates the 'pipe' format using callables for lineabove and linebelowheader. ```python # pipe format uses a callable for lineabove and linebelowheader _table_formats["pipe"] = TableFormat( lineabove=_pipe_line_with_colons, # Function linebelowheader=_pipe_line_with_colons, # ... ) ``` -------------------------------- ### Pipeline Usage Examples Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Shows how to use tabulate with standard input (stdin) and pipe its output to other commands or files. ```bash # From stdin cat data.txt | tabulate -1 -f grid # Process and pipe output tabulate data.csv -f pipe | tee output.txt # Chain with other commands curl https://example.com/data.csv | tabulate -r csv -f html > result.html ``` -------------------------------- ### Usage of tabulate_formats Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Examples demonstrating how to check for supported formats, iterate over them, and use them with the tabulate function. ```python from tabulate import tabulate, tabulate_formats # Check if a format is supported if "html" in tabulate_formats: print("HTML format is supported") # Iterate over all formats for fmt in tabulate_formats: print(f"Supported format: {fmt}") # Use a format from the list data = [["Alice", 24], ["Bob", 19]] for fmt in ["simple", "grid", "pipe"]: if fmt in tabulate_formats: print(f"\n{fmt} format:") print(tabulate(data, tablefmt=fmt)) ``` -------------------------------- ### Format-specific output examples Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Provides examples of generating table output in various formats including plain text, markdown, data exchange, markup, and wiki formats. ```python from tabulate import tabulate data = [["Alice", 24], ["Bob", 19]] headers = ["Name", "Age"] # Plain text formats simple = tabulate(data, headers=headers, tablefmt="simple") grid = tabulate(data, headers=headers, tablefmt="grid") # Markdown-compatible markdown = tabulate(data, headers=headers, tablefmt="pipe") # Data exchange formats tsv = tabulate(data, headers=headers, tablefmt="tsv") csv = tabulate(data, headers=headers, tablefmt=simple_separated_format(",")) # Markup formats html = tabulate(data, headers=headers, tablefmt="html") latex = tabulate(data, headers=headers, tablefmt="latex") # Wiki formats mediawiki = tabulate(data, headers=headers, tablefmt="mediawiki") ``` -------------------------------- ### Install tabulate with wide character support Source: https://github.com/astanin/python-tabulate/blob/master/README.md Install the tabulate library with the necessary dependency for wide character support, which is required for proper alignment of tables containing fullwidth CJK characters. ```shell pip install tabulate[widechars] ``` -------------------------------- ### Tabulate with Different Output Formats Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Presents examples of generating tables in various predefined formats, including grid, pipe (GitHub markdown), TSV, and HTML. ```python data = [["Alice", 24], ["Bob", 19]] # Grid format print(tabulate(data, tablefmt="grid")) # Pipe format (GitHub markdown) print(tabulate(data, headers=["Name", "Age"], tablefmt="pipe")) # CSV format print(tabulate(data, tablefmt="tsv")) # HTML format print(tabulate(data, tablefmt="html")) ``` -------------------------------- ### Paginate Large Datasets Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Demonstrates pagination for large datasets by processing data in chunks. This example shows how to display a subset of data for a given page. ```python from tabulate import tabulate import time # For very large tables, consider: # 1. Pagination # 2. Selective columns # 3. Summary statistics instead of full tables # Pagination example data = list(range(1000)) page_size = 10 page_num = 0 start = page_num * page_size end = start + page_size page_data = [[i, i*2] for i in data[start:end]] print(tabulate(page_data, headers=["Value", "Double"], tablefmt="simple")) # Or use generators def data_generator(): for i in range(100): yield [i, i*2] # Convert to list when needed print(tabulate(list(data_generator())[:10], tablefmt="simple")) ``` -------------------------------- ### Format Inheritance Example Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/architecture.md Demonstrates format inheritance where one format name is an alias for another. The 'github' format is set as an alias for the 'pipe' format, resulting in identical output. ```python _table_formats["github"] = _table_formats["pipe"] ``` -------------------------------- ### Configure Integer Formatting for All Columns Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Use a single format string to apply to all integer columns. This example sets all integers to be displayed in hexadecimal format. ```python intfmt="x" # Hexadecimal for all integer columns ``` -------------------------------- ### Configure Integer Formatting for Specific Columns Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Provide a list or tuple of format strings to apply different formatting to specific integer columns by their index. This example formats the first column as decimal and the second as hexadecimal. ```python intfmt=["d", "x"] # Col 0: decimal, Col 1: hexadecimal ``` -------------------------------- ### TSV Data Example Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Example of data formatted as Tab-Separated Values (TSV). ```text Alice 24 Bob 19 ``` -------------------------------- ### Command-Line Usage of tabulate Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/index.md Examples of using the tabulate command-line utility to format data files. Supports specifying headers, output formats, and writing to a file. ```bash # Format a file tabulate -1 data.csv # Specify format tabulate -f grid data.txt # Use headers tabulate --headers "Name,Age" data.txt # Write to file tabulate data.csv -o output.txt ``` -------------------------------- ### Dynamic Version Detection Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/architecture.md This code attempts to detect the package version from installed metadata or a local `_version.py` file, falling back to 'unknown' if neither is found. ```python try: __version__ = version("tabulate") # From installed package except PackageNotFoundError: try: from ._version import version as __version__ # From _version.py except ImportError: __version__ = "unknown" ``` -------------------------------- ### Run Tox Environments with Extra Dependencies Source: https://github.com/astanin/python-tabulate/blob/master/README.md Enable NumPy and Pandas tests by running tox with extra environments. This may require installing these packages in new virtual environments. ```shell tox -e py311-extra,py312-extra ``` -------------------------------- ### Numeric Format Specification Examples Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/architecture.md Illustrates Python's string format specifiers for controlling the output of floating-point and integer numbers. ```python floatfmt examples: "g" → General format ".2f" → Fixed decimal ".2e" → Exponential ".2%" → Percentage intfmt examples: "" → Default "d" → Decimal "x" → Hexadecimal "o" → Octal "b" → Binary ``` -------------------------------- ### Create Custom Lines Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/types.md Examples of creating different Line objects for table formatting. Used when defining custom TableFormat objects. ```python from tabulate import Line, TableFormat, DataRow, tabulate # Create a simple grid line line_above = Line("+", "-", "+", "+") # Create a grid line below header (with "=" instead of "-") line_below_header = Line("+", "=", "+", "+") # Use in a TableFormat ``` -------------------------------- ### Create Custom DataRow Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/types.md Example of creating a custom DataRow for table formatting. Typically used when defining custom TableFormat objects. ```python from tabulate import DataRow, TableFormat, Line, tabulate # Create a custom row format where cells are separated by " | " data_row = DataRow("|", "|", "|") header_row = DataRow("|", "|", "|") # Use in a TableFormat (see TableFormat documentation) ``` -------------------------------- ### Configure Float Formatting for All Columns Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Use a single format string to apply to all floating-point columns. This example sets all floats to display with two decimal places. ```python floatfmt=".2f" # All columns: 2 decimal places ``` -------------------------------- ### Format a DataFrame Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/index.md Use this snippet to format a pandas DataFrame into a grid table. It requires pandas and tabulate to be installed. ```python import pandas as pd from tabulate import tabulate df = pd.read_csv("data.csv") print(tabulate(df, headers="keys", tablefmt="grid")) ``` -------------------------------- ### Configure Float Formatting for Specific Columns Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Provide a list or tuple of format strings to apply different formatting to specific floating-point columns by their index. This example formats the first column with 2 decimal places and the second with exponential notation. ```python floatfmt=[".2f", ".1e"] # Col 0: 2 decimals, Col 1: 1 decimal in exponent ``` -------------------------------- ### Basic table formatting Source: https://github.com/astanin/python-tabulate/blob/master/README.md Format a list of lists into a plain-text table using the tabulate function. The formatting is guided by the data itself. ```python from tabulate import tabulate table = [["Sun",696000,1989100000],["Earth",6371,5973.6], ["Moon",1737,73.5],["Mars",3390,641.85]] print(tabulate(table)) ``` -------------------------------- ### Configure Missing Value Replacement for All Columns Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Use a single string to replace None or missing values in all columns. This example replaces missing values with 'N/A'. ```python missingval="N/A" # All columns: "N/A" ``` -------------------------------- ### Custom Number Formatting with floatfmt Source: https://github.com/astanin/python-tabulate/blob/master/README.md Applies custom formatting to floating-point numbers using the `floatfmt` argument. This example formats to 4 decimal places. ```pycon >>> print(tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")) -- ------ pi 3.1416 e 2.7183 -- ------ ``` -------------------------------- ### Process CSV from Command Line Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/index.md Process a CSV file from the command line using the tabulate CLI. This example shows reading a CSV file and outputting it in grid format. ```bash tabulate -r csv -1 -f grid data.csv ``` -------------------------------- ### Configure Missing Value Replacement for Specific Columns Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Provide a list or tuple of strings to replace None or missing values in specific columns by their index. This example replaces missing values in the first column with '—' and in the second with 'unknown'. ```python missingval=["—", "unknown"] # Col 0: "—", Col 1: "unknown" ``` -------------------------------- ### Handle Headers with --headers Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Illustrates different ways to handle headers using the --headers option, including using the first row, providing explicit names, or using keys from JSONL. ```bash # Use first row as headers tabulate -1 data.csv # or --headers firstrow ``` ```bash # Explicit headers for CSV tabulate -H "Name,Age,Score" data.txt ``` ```bash # JSONL with keys tabulate -r jsonl -H "keys" data.jsonl ``` ```bash # JSONL with custom header names tabulate -r jsonl -H "user_id:ID,user_name:Name" data.jsonl ``` -------------------------------- ### Tabulate with Formatting Options Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Shows how to apply formatting options, such as floating-point precision (`floatfmt`) and table format, to customize the output. ```python data = [["pi", 3.14159], ["e", 2.71828]] print(tabulate(data, headers=["Symbol", "Value"], floatfmt=".2f", tablefmt="grid")) ``` -------------------------------- ### Basic Tabulate Formatting Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Demonstrates basic table creation with specified decimal places for floats and right alignment for numbers. ```python from tabulate import tabulate data = [["Alice", 24.567], ["Bob", 19.234]] headers = ["Name", "Score"] # Simple format with 2 decimal places print(tabulate(data, headers=headers, floatfmt=".2f")) # Grid format with right alignment print(tabulate(data, headers=headers, tablefmt="grid", numalign="right")) # No headers, centered alignment print(tabulate(data, tablefmt="simple", stralign="center")) ``` -------------------------------- ### Programmatic format selection Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Shows how to check for supported formats, generate output in multiple formats, and allow user selection of a table format. ```python from tabulate import tabulate, tabulate_formats # Check if format is supported if "html" in tabulate_formats: print("HTML format available") # Generate output in multiple formats data = [["a", 1], ["b", 2]] for fmt in ["simple", "grid", "html"]: print(f" {fmt} format:") print(tabulate(data, tablefmt=fmt)) # User-selectable format user_format = input(f"Choose format ({', '.join(tabulate_formats[:5])}..."): ") if user_format in tabulate_formats: print(tabulate(data, tablefmt=user_format)) ``` -------------------------------- ### Format tables from dataclasses Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Shows how to format tables from a list of dataclass instances, using field names as headers. ```python from dataclasses import dataclass from tabulate import tabulate @dataclass class Person: name: str age: int data = [ Person("Alice", 24), Person("Bob", 19) ] # Field names become headers print(tabulate(data, headers="keys")) ``` -------------------------------- ### Processing Multiple Files Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Demonstrates processing multiple input files by listing them or using a loop. ```bash # Process multiple files tabulate file1.txt file2.txt -f grid # Or individually for file in *.txt; do echo "=== $file ===" tabulate "$file" done ``` -------------------------------- ### Format a simple table Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Demonstrates formatting a simple table from a list of lists, with and without headers, and using the 'grid' format. ```python # List of lists data = [["Alice", 24], ["Bob", 19]] print(tabulate(data)) # With headers print(tabulate(data, headers=["Name", "Age"])) # Different format print(tabulate(data, headers=["Name", "Age"], tablefmt="grid")) ``` -------------------------------- ### Set Output Table Format with -f Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Demonstrates setting the output table format using the -f or --format option with various format names like grid, pipe, html, and latex. ```bash # Grid format tabulate -f grid data.txt ``` ```bash # GitHub markdown tabulate -f pipe data.csv ``` ```bash # HTML tabulate -f html data.txt ``` ```bash # LaTeX tabulate -f latex data.csv ``` -------------------------------- ### Default Table Formatting Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Use this for basic table creation with default float formatting. ```python from tabulate import tabulate data = [ ["Alice", 24], ["Bob", 19] ] print(tabulate(data, headers=["Name", "Age"])) ``` -------------------------------- ### Run Specific Tox Environments Source: https://github.com/astanin/python-tabulate/blob/master/README.md Execute tox tests for specific Python environments like 3.11 and 3.12. Ensure tox is installed and Python versions are available. ```shell tox -e py311,py312 ``` -------------------------------- ### Show Help Message Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Displays the help message for the tabulate CLI. Use either the -h or --help flag. ```bash tabulate -h tabulate --help ``` -------------------------------- ### Importing Public API Items Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Demonstrates how to import all public API items directly from the tabulate package. ```python from tabulate import tabulate, tabulate_formats, simple_separated_format, SEPARATING_LINE ``` -------------------------------- ### Column Width and Text Wrapping Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Demonstrates how to control column widths and enable text wrapping for long content. ```python import pandas as pd data = [ ["Issue 1", "This is a very long description that needs to be wrapped"], ["Issue 2", "Another long text for demonstration purposes"] ] print(tabulate( data, headers=["Issue", "Description"], maxcolwidths=[None, 30], # Wrap description at 30 chars tablefmt="grid" )) ``` -------------------------------- ### Calculate String Length with ANSI Support Source: https://github.com/astanin/python-tabulate/blob/master/README.md Demonstrates how tabulate calculates string length by removing ANSI escape sequences to get the printable length. The original styling is preserved in the final output. ```python >>> len('\033[31mthis text is red\033[0m') # printable length is 16 25 ``` ```python >>> len('\x1b]8;;https://example.com\x1b\example\x1b]8;;\x1b\') # display length is 7, showing 'example' 40 ``` -------------------------------- ### Column Width Calculation Algorithm Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/architecture.md Outlines the steps involved in determining the optimal width for each column, considering content, padding, and minimum constraints. ```text For each column: 1. Find maximum content width - Consider all cells in column - Account for wrapping if maxcolwidths is set 2. Add padding (2 × format.padding) 3. Apply minimum width constraints 4. Return column width ``` -------------------------------- ### Basic Usage of tabulate CLI Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Demonstrates basic invocation of the tabulate command for reading from standard input, a file, multiple files, or writing to an output file. ```bash # Read from stdin echo "Alice 24\nBob 19" | tabulate ``` ```bash # Read from file tabulate mydata.txt ``` ```bash # Multiple files tabulate file1.txt file2.txt ``` ```bash # Write to output file tabulate data.txt -o output.txt ``` -------------------------------- ### Disable wide character support in tabulate Source: https://github.com/astanin/python-tabulate/blob/master/README.md Programmatically disable wide character support in the tabulate library by setting the global module-level flag WIDE_CHARS_MODE to False. This is useful if the wcwidth library is installed but wide character support is not desired. ```python import tabulate tabulate.WIDE_CHARS_MODE = False ``` -------------------------------- ### Basic Python Usage of tabulate Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/index.md Demonstrates basic table creation and formatting using the tabulate function in Python. Supports various output formats like 'grid'. ```python from tabulate import tabulate # Simple table data = [["Alice", 24], ["Bob", 19]] print(tabulate(data, headers=["Name", "Age"])) # With formatting print(tabulate(data, headers=["Name", "Age"], tablefmt="grid")) ``` -------------------------------- ### Custom Integer Formatting Source: https://github.com/astanin/python-tabulate/blob/master/README.md Demonstrates custom formatting for integers using the `intfmt` argument, such as adding thousands separators. ```pycon >>> print(tabulate([["a",1000],["b",90000]], intfmt=",")) - ------ a 1,000 b 90,000 - ``` -------------------------------- ### Type Deduction and Missing Values Example Source: https://github.com/astanin/python-tabulate/blob/master/README.md Demonstrates how tabulate aligns columns based on data types, including numerical alignment on decimal points and handling of missing values. The deduced type influences rendering, and precision can be maintained by ensuring columns contain strings or by explicit conversion. ```python >>> from fractions import Fraction >>> test_table = [ ... [None, "1.23423515351", Fraction(1, 3)], ... [Fraction(56789, 1000000), 12345.1, b"abc"], ... ["", b"", None], ... [Fraction(10000, 3), None, ""], ... ] >>> print(tabulate(test_table, floatfmt=",.5g", missingval="?")) ------------ ----------- --- ? 1.2342 1/3 0.056789 12,345 abc ? 3,333.3 ? ------------ ----------- --- ``` -------------------------------- ### Tabulate Command Line Utility Usage Source: https://github.com/astanin/python-tabulate/blob/master/README.md Shows the available options for the tabulate command-line utility, including input file formats, output formatting, and header options. ```bash Usage: tabulate [options] [FILE ...] Pretty-print tabular data. Use Python module for more features. FILE a filename of the file with tabular data; if "-" or missing, read data from stdin. Options: -h, --help show this message INPUT: -r, --read FILEFORMAT parse input FILEs as: rsv (REGEXP-separated values, default), csv (comma-separated valued, Excel dialect), jsonl (one JSON object per line) -s REGEXP, --sep REGEXP column separator for rsv data (default: whitespace) FORMAT: --headers HEADERS HEADERS can be one of: "firstrow" (for csv and rsv data), "keys" (for jsonl data), "HEADER1,HEADER2,..." (for csv and rsv data), "KEY1:HEADER1,KEY2:HEADER2,..." (for jsonl data) -1 use the first row of input data as a table header (the same as --headers firstrow) -F FPFMT, --float FPFMT floating point number format (default: g) -I INTFMT, --int INTFMT integer point number format (default: "") -f FMT, --format FMT set output table format (default: simple) Supported output formats: asciidoc, colon_grid, double_grid, double_outline, fancy_grid, fancy_outline, github, grid, heavy_grid, heavy_outline, html, jira, latex, latex_booktabs, latex_longtable, latex_raw, mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, outline, pipe, plain, presto, pretty, psql, rounded_grid, rounded_outline, rst, simple, simple_grid, simple_outline, textile, tsv, unsafehtml. OUTPUT: -o FILE, --output FILE print table to FILE (default: stdout) ``` -------------------------------- ### Tabulate with Custom Headers Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Shows how to provide custom headers for the table using a list of strings. This is useful for labeling columns clearly. ```python data = [["Alice", 24], ["Bob", 19]] print(tabulate(data, headers=["Name", "Age"]))... ``` -------------------------------- ### Multiple Output Formats Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Demonstrates saving data from a CSV file into different output formats like grid and HTML. ```bash tabulate -f grid data.csv -o grid.txt tabulate -f html data.csv -o table.html ``` -------------------------------- ### Tabulate with Dictionary Data and Keys as Headers Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Demonstrates using a list of dictionaries as data, with dictionary keys automatically used as table headers. ```python data = [ {"name": "Alice", "age": 24}, {"name": "Bob", "age": 19} ] print(tabulate(data, headers="keys"))... ``` -------------------------------- ### Format Integers with -I Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Illustrates formatting integers using the -I or --int option with Python format specifications like decimal, hexadecimal, and octal. ```bash # Decimal (default) tabulate -I d data.txt ``` ```bash # Hexadecimal tabulate -I x data.txt ``` ```bash # Octal tabulate -I o data.txt ``` -------------------------------- ### Specify Input File Format with -r Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Shows how to specify the input file format using the -r or --read option, including CSV and JSON Lines. ```bash # CSV input tabulate -r csv data.csv ``` ```bash # JSON Lines input tabulate -r jsonl data.jsonl ``` ```bash # RSV with custom separator tabulate -s ',' data.rsv # Comma-separated ``` -------------------------------- ### Format tables from JSON files Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Demonstrates formatting tables from JSON files, including standard JSON arrays of objects and JSON Lines (JSONL) format. ```python import json from tabulate import tabulate # JSON array of objects with open("data.json") as f: data = json.load(f) # data is list of dicts print(tabulate(data, headers="keys")) # JSON Lines (JSONL) lines = [] with open("data.jsonl") as f: for line in f: lines.append(json.loads(line)) print(tabulate(lines, headers="keys")) ``` -------------------------------- ### Custom Separated Formats Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Illustrates creating tables with custom column separators like pipes or semicolons. ```python from tabulate import simple_separated_format data = [["Alice", 24], ["Bob", 19]] # Pipe-separated values print(tabulate(data, tablefmt=simple_separated_format("|"))) # Semicolon-separated with headers print(tabulate(data, headers=["Name", "Age"], tablefmt=simple_separated_format(";"))) ``` -------------------------------- ### Format tables from NumPy arrays Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Demonstrates formatting tables from a 2D NumPy array and a NumPy record array, with options for headers. ```python import numpy as np from tabulate import tabulate # 2D array data = np.array([[1, 2], [3, 4], [5, 6]]) print(tabulate(data, headers=["Col 1", "Col 2"])) # Record array (structured array) data = np.array( [(1, 2.5), (3, 4.5)], dtype=[("id", int), ("score", float)] ) print(tabulate(data, headers="keys")) ``` -------------------------------- ### Format tables from dictionaries Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Demonstrates formatting tables from a list of dictionaries (keys as headers) and a dictionary of lists (keys as headers). ```python from tabulate import tabulate # List of dicts (dict keys become column headers) data = [ {"name": "Alice", "age": 24}, {"name": "Bob", "age": 19} ] print(tabulate(data, headers="keys")) # Dict of lists (keys become column headers) data = { "name": ["Alice", "Bob"], "age": [24, 19] } print(tabulate(data, headers="keys")) # Explicitly specify headers print(tabulate(data, headers=["Name", "Age"]))) ``` -------------------------------- ### Specify Column Alignment with -C Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Demonstrates specifying column alignment using the -C or --colalign option with alignment values like left, center, right, and decimal. ```bash # Left, center, right alignment tabulate --colalign left center right data.csv ``` ```bash # For specific columns (unspecified default to auto) tabulate -C right right data.txt ``` -------------------------------- ### Create a Markdown Table Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/index.md Generate a Markdown formatted table from a list of lists. Ensure the tabulate library is imported. ```python from tabulate import tabulate data = [["a", 1], ["b", 2]] markdown = tabulate(data, headers=["Col1", "Col2"], tablefmt="pipe") ``` -------------------------------- ### Use Plain Format for Performance Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Use this to improve performance with large tables. The 'plain' format is faster than complex grid variants. ```python # Use simpler format (faster) tabulate(data, tablefmt="plain") ``` -------------------------------- ### Format tables from CSV files Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Shows how to read data from a CSV file and format it into a table, using the first row as headers. ```python import csv from tabulate import tabulate # Read CSV file with open("data.csv") as f: reader = csv.reader(f) data = list(reader) # Use first row as headers print(tabulate(data, headers="firstrow")) ``` -------------------------------- ### Create Custom TSV Format with Headers using simple_separated_format Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Demonstrates using `simple_separated_format` to create a tab-separated values table that includes custom headers. ```python data = [["Alice", 24], ["Bob", 19]] tsv_fmt = simple_separated_format("\t") print(tabulate(data, headers=["Name", "Age"], tablefmt=tsv_fmt)) ``` -------------------------------- ### Simple Separated Formats Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Create custom table formats using simple delimiters like tabs or pipes. ```python from tabulate import tabulate, simple_separated_format data = [["a", 1], ["b", 2]] headers = ["Letter", "Number"] # Tab-separated tsv_fmt = simple_separated_format("\t") print(tabulate(data, headers=headers, tablefmt=tsv_fmt)) ``` ```python # Pipe-separated pipe_fmt = simple_separated_format("|") print(tabulate(data, headers=headers, tablefmt=pipe_fmt)) ``` ```python # Custom format custom_fmt = simple_separated_format(" :: ") print(tabulate(data, headers=headers, tablefmt=custom_fmt)) ``` -------------------------------- ### Automatic Multiline Wrapping with maxcolwidths Source: https://github.com/astanin/python-tabulate/blob/master/README.md Demonstrates how to automatically wrap text in a table column to a specified maximum width. Use `None` for columns where wrapping is not needed. ```pycon >>> print(tabulate([["John Smith", "Middle Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 8])) +------------+---------+ | Name | Title | +============+=========+ | John Smith | Middle | | | Manager | +------------+---------+ ``` -------------------------------- ### Custom Global and Column Alignment Source: https://github.com/astanin/python-tabulate/blob/master/README.md Shows how to set custom alignment for all columns globally using `colglobalalign` and specify alignment for individual columns using `colalign`. ```pycon >>> print(tabulate([[1,2,3,4],[111,222,333,444]], colglobalalign='center', colalign = ('global','left','right'))) --- --- --- --- 1 2 3 4 111 222 333 444 --- --- --- --- ``` -------------------------------- ### PSQL Table Format Source: https://github.com/astanin/python-tabulate/blob/master/README.md Generates tables in a format similar to PostgreSQL's psql command-line client. Useful for SQL-like table representations. ```python >>> print(tabulate(table, headers, tablefmt="psql")) +--------+-------+ | item | qty | |--------+-------| | spam | 42 | | eggs | 451 | | bacon | 0 | +--------+-------+ ``` -------------------------------- ### Format tables from named tuples Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Illustrates formatting tables from a list of named tuples, where field names are used as headers. ```python from collections import namedtuple from tabulate import tabulate Person = namedtuple("Person", ["name", "age"]) data = [ Person("Alice", 24), Person("Bob", 19) ] # Field names become headers print(tabulate(data, headers="keys")) ``` -------------------------------- ### Simple Table Format Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Minimal table format with dashes for separation. Useful for basic console output. ```text ----- ------ Alice 24 Bob 19 ----- ------ ``` -------------------------------- ### Saving Different Output Formats Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Demonstrates saving the output of tabulate in multiple formats (grid, pipe, html, latex) to different files using the -o option. ```bash # Generate multiple format outputs tabulate -r csv -f grid data.csv -o grid.txt tabulate -r csv -f pipe data.csv -o markdown.txt tabulate -r csv -f html data.csv -o table.html tabulate -r csv -f latex data.csv -o table.tex ``` -------------------------------- ### Write Output to File with -o Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Shows how to write the output of the tabulate command to a specified file using the -o or --output option. ```bash # Write to file tabulate data.csv -o output.txt ``` ```bash # Pipe to another command tabulate data.csv | less ``` -------------------------------- ### Table formatting using the first row as headers Source: https://github.com/astanin/python-tabulate/blob/master/README.md Use the first row of the data as the table headers. This is useful when the header information is included in the dataset. ```python print(tabulate([["Name","Age"],["Alice",24],["Bob",19]], headers="firstrow")) ``` -------------------------------- ### Column-Specific Number Formatting Source: https://github.com/astanin/python-tabulate/blob/master/README.md Shows how to apply different number formatting to individual columns using a list or tuple for the `floatfmt` argument. ```pycon >>> print(tabulate([[0.12345, 0.12345, 0.12345]], floatfmt=(".1f", ".3f"))) --- ----- 0.1 0.123 --- ``` -------------------------------- ### Format tables from pandas DataFrames Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Illustrates formatting pandas DataFrames into tables, with options for using column names as headers and controlling index display. ```python import pandas as pd from tabulate import tabulate # DataFrame df = pd.DataFrame({ "name": ["Alice", "Bob"], "age": [24, 19] }) # Column names become headers print(tabulate(df, headers="keys")) # Without index print(tabulate(df, headers="keys", showindex=False)) # With index print(tabulate(df, headers="keys", showindex="always")) ``` -------------------------------- ### Formatting Numbers and Alignment Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Applies number formatting to two decimal places using -F ".2f" and custom column alignment using --colalign. ```bash # Numbers with 2 decimal places tabulate -r csv -F ".2f" numeric_data.csv # Custom column alignment tabulate -r csv --colalign left right center data.csv # Both header and float formatting tabulate -r csv -1 -F ".2f" data.csv ``` -------------------------------- ### Tabulate with Column Width Limiting and Wrapping Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Demonstrates limiting the maximum width of columns and enabling text wrapping for long content within cells using `maxcolwidths`. ```python data = [["Issue", "Description"], [1, "This is a long description that needs wrapping"]] print(tabulate(data, headers="firstrow", maxcolwidths=[None, 20], tablefmt="grid")) ``` -------------------------------- ### JSON Lines Input with Custom Headers Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Maps JSON keys to custom header names for the output table. Use the -H "key:Header Name" format. ```bash # Map JSON keys to custom header names tabulate -r jsonl -H "name:Full Name,age:Years" data.jsonl ``` -------------------------------- ### Tabulate with Row Indices Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Illustrates how to include row indices in the table output by setting `showindex` to 'always'. ```python data = [["Alice", 24], ["Bob", 19]] print(tabulate(data, showindex="always")) ``` -------------------------------- ### Tabulate Performance Benchmark Source: https://github.com/astanin/python-tabulate/blob/master/README.md Compares the performance of tabulate against other table formatting libraries using a mini-benchmark. Results are shown in microseconds and relative time. ```text ================================== ========== =========== Table formatter time, μs rel. time ================================== ========== =========== csv to StringIO 11.9 1.0 join with tabs and newlines 12.1 1.0 PrettyTable (3.17.0) 468.0 39.3 tabulate (0.10.0) 553.4 46.5 tabulate (0.10.0, WIDE_CHARS_MODE) 612.2 51.4 texttable (1.7.0) 1071.4 90.0 ================================== ========== =========== ``` -------------------------------- ### Different Line Styles Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/types.md Demonstrates various styles for horizontal lines using the Line named tuple, including standard grid, heavy grid, Unicode box drawing, and minimal styles. ```python from tabulate import Line # Standard grid simple_line = Line("+", "-", "+", "+") # Heavy grid heavy_line = Line("\u2550", "\u2550", "\u2566", "\u2550") # Unicode box drawing rounded_line = Line("\u256d", "\u2500", "\u252c", "\u256e") # Minimal minimal_line = Line("", "-", " ", "") ``` -------------------------------- ### Pretty Table Format Source: https://github.com/astanin/python-tabulate/blob/master/README.md Mimics the output of the PrettyTables library. This format is visually appealing and easy to read. ```python >>> print(tabulate(table, headers, tablefmt="pretty")) +-------+-----+ | item | qty | +-------+-----+ | spam | 42 | | eggs | 451 | | bacon | 0 | +-------+-----+ ``` -------------------------------- ### Tabulate with Column-Specific Alignment Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Demonstrates setting specific text alignment for each column using the `colalign` parameter. This allows fine-grained control over text positioning. ```python data = [["left", "center", "right"]] print(tabulate(data, colalign=["left", "center", "right"], tablefmt="grid")) ``` -------------------------------- ### HTML Table Rendering in Jupyter Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/types.md Demonstrates how tabulate produces HTML output that is automatically rendered as an HTML table in Jupyter notebooks. The raw HTML string can be accessed via the .str property. ```python from tabulate import tabulate data = [["Alice", 24], ["Bob", 19]] result = tabulate(data, headers=["Name", "Age"], tablefmt="html") # In Jupyter, this displays as an HTML table print(result) # Access the raw HTML string html_string = result.str ``` -------------------------------- ### Custom Header Alignment Source: https://github.com/astanin/python-tabulate/blob/master/README.md Demonstrates how to control header alignment independently from column alignment using `headersglobalalign` and `headersalign`. ```pycon >>> print(tabulate([[1,2,3,4,5,6],[111,222,333,444,555,666]], colglobalalign = 'center', colalign = ('left',), headers = ['h','e','a','d','e','r'], headersglobalalign = 'right', headersalign = ('same','same','left','global','center'))) h e a d e r --- --- --- --- --- --- 1 2 3 4 5 6 111 222 333 444 555 666 ``` -------------------------------- ### Basic Tabulate Usage Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/api-reference.md Demonstrates the fundamental usage of the tabulate function with simple list data. No special headers or formats are applied. ```python from tabulate import tabulate data = [["Alice", 24], ["Bob", 19]] print(tabulate(data)) ``` -------------------------------- ### Jira Table Format Source: https://github.com/astanin/python-tabulate/blob/master/README.md Generates tables compatible with Atlassian Jira markup language. Ideal for issue tracking and project documentation within Jira. ```python >>> print(tabulate(table, headers, tablefmt="jira")) || item || qty || | spam | 42 | | eggs | 451 | | bacon | 0 | ``` -------------------------------- ### PostgreSQL psql Format Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md PostgreSQL `\pset` format. Uses plus signs and hyphens for borders, with a distinct line separating header from data. ```text +-------+-----+ | Alice | 24 | |-------+-----| | Bob | 19 | +-------+-----+ ``` -------------------------------- ### Plain Table Format Source: https://github.com/astanin/python-tabulate/blob/master/README.md Generates a table without any pseudo-graphics for lines. Useful for simple text output. ```pycon >>> table = [["spam",42],["eggs",451],["bacon",0]] >>> headers = ["item", "qty"] >>> print(tabulate(table, headers, tablefmt="plain")) item qty spam 42 eggs 451 bacon 0 ``` -------------------------------- ### Format Floating-Point Numbers with -F Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Shows how to format floating-point numbers using the -F or --float option with Python format specifications. ```bash # 2 decimal places tabulate -F ".2f" data.csv ``` ```bash # Scientific notation tabulate -F ".2e" data.csv ``` ```bash # Percentage format tabulate --float ".1%" data.csv ``` ```bash # General format with 3 significant digits tabulate -F ".3g" data.txt ``` -------------------------------- ### Advanced Column Alignment Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Shows how to apply different alignment strategies to individual columns and headers. ```python # Different alignments per column print(tabulate( data, headers=headers, colalign=["left", "right"], # Name left, Score right tablefmt="grid" )) # Header alignment independent of column alignment print(tabulate( data, headers=headers, colalign=["left", "decimal"], headersalign=["center", "center"], tablefmt="pipe" )) ``` -------------------------------- ### Table formatting using keys as headers Source: https://github.com/astanin/python-tabulate/blob/master/README.md Use the keys from a dictionary or column indices as headers. This works for dictionaries, NumPy record arrays, and lists of dictionaries. ```python print(tabulate({"Name": ["Alice", "Bob"], "Age": [24, 19]}, headers="keys")) ``` -------------------------------- ### Display Database Query Results Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Fetch data from an SQLite database and display it using the 'grid' table format. Ensure the database connection and cursor are properly managed. ```python import sqlite3 from tabulate import tabulate conn = sqlite3.connect(":memory:") cursor = conn.cursor() # Create sample table cursor.execute(""" CREATE TABLE users (id INTEGER, name TEXT, email TEXT, age INTEGER) """) cursor.execute("INSERT INTO users VALUES (1, 'Alice', 'alice@example.com', 24)") cursor.execute("INSERT INTO users VALUES (2, 'Bob', 'bob@example.com', 19)") conn.commit() # Fetch and display cursor.execute("SELECT * FROM users") columns = [description[0] for description in cursor.description] rows = cursor.fetchall() print(tabulate(rows, headers=columns, tablefmt="grid")) ``` -------------------------------- ### HTML Output to File Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/cli-reference.md Generates an HTML file from CSV data. The output is redirected to table.html. ```bash tabulate -r csv -f html -1 data.csv > table.html # Creates an HTML file with table markup ``` -------------------------------- ### Simple Outline Table Format Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/configuration.md Single-line Unicode box without lines between rows. Ideal for a minimalist bordered table. ```text ┌───────┬─────┐ │ Alice │ 24 │ │ Bob │ 19 │ └───────┴─────┘ ``` -------------------------------- ### Create Custom Table Format Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/types.md Define a custom table format with specific line and row styles using TableFormat, Line, and DataRow. This allows for fine-grained control over table appearance. ```python from tabulate import TableFormat, Line, DataRow, tabulate # Create a custom format with specific line and row styles custom_format = TableFormat( lineabove=Line("+", "-", "+", "+"), linebelowheader=Line("|", "-", "+", "|"), linebetweenrows=None, linebelow=Line("+", "-", "+", "+"), headerrow=DataRow("|", "|", "|"), datarow=DataRow("|", "|", "|"), padding=1, with_header_hide=None ) data = [["Alice", 24], ["Bob", 19]] print(tabulate(data, headers=["Name", "Age"], tablefmt=custom_format)) ``` -------------------------------- ### Simple Table Format Source: https://github.com/astanin/python-tabulate/blob/master/README.md The default table format, similar to Pandoc's simple tables. Uses basic lines for structure. ```pycon >>> print(tabulate(table, headers, tablefmt="simple")) item qty ------ ----- spam 42 eggs 451 bacon 0 ``` -------------------------------- ### Format Benchmark Results Source: https://github.com/astanin/python-tabulate/blob/master/_autodocs/integration-guide.md Display benchmark results with multiple runs for each algorithm. The 'floatfmt' argument is used to format floating-point numbers to three decimal places. ```python from tabulate import tabulate import time # Simulate benchmark results results = [ ["Algorithm A", 1.23, 1.24, 1.22], ["Algorithm B", 0.98, 1.01, 0.99], ["Algorithm C", 1.56, 1.54, 1.57] ] print(tabulate( results, headers=["Algorithm", "Run 1 (s)", "Run 2 (s)", "Run 3 (s)"], floatfmt=".3f", tablefmt="grid" )) ```