0
# Tabulate
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: tabulate
7
- **Language**: Python
8
- **Installation**: `pip install tabulate`
9
- **Optional Dependencies**: `wcwidth` for wide character (CJK) support
10
11
## Core Imports
12
13
```python
14
from tabulate import tabulate
15
```
16
17
Import specific utilities:
18
19
```python
20
from tabulate import tabulate, tabulate_formats, simple_separated_format
21
```
22
23
Import constants for advanced usage:
24
25
```python
26
from tabulate import SEPARATING_LINE, MIN_PADDING, PRESERVE_WHITESPACE, WIDE_CHARS_MODE
27
```
28
29
Import data structures for custom formatting:
30
31
```python
32
from tabulate import Line, DataRow, TableFormat
33
```
34
35
## Basic Usage
36
37
```python
38
from tabulate import tabulate
39
40
# Simple table from list of lists
41
table = [["Sun", 696000, 1989100000],
42
["Earth", 6371, 5973.6],
43
["Moon", 1737, 73.5],
44
["Mars", 3390, 641.85]]
45
46
print(tabulate(table))
47
# Output:
48
# ----- ------ -------------
49
# Sun 696000 1.9891e+09
50
# Earth 6371 5973.6
51
# Moon 1737 73.5
52
# Mars 3390 641.85
53
# ----- ------ -------------
54
55
# Table with headers
56
print(tabulate(table, headers=["Planet", "R (km)", "mass (x 10^29 kg)"]))
57
# Output:
58
# Planet R (km) mass (x 10^29 kg)
59
# -------- -------- -------------------
60
# Sun 696000 1.9891e+09
61
# Earth 6371 5973.6
62
# Moon 1737 73.5
63
# Mars 3390 641.85
64
65
# Different output formats
66
print(tabulate(table, headers=["Planet", "R (km)", "mass"], tablefmt="grid"))
67
print(tabulate(table, headers=["Planet", "R (km)", "mass"], tablefmt="html"))
68
print(tabulate(table, headers=["Planet", "R (km)", "mass"], tablefmt="markdown"))
69
```
70
71
## Architecture
72
73
Tabulate uses a flexible formatting system built around these core components:
74
75
- **TableFormat**: Named tuple defining complete table structure (lines, rows, padding)
76
- **Line**: Named tuple for horizontal line formatting (begin, hline, sep, end)
77
- **DataRow**: Named tuple for row formatting (begin, sep, end)
78
- **Format Registry**: Dictionary mapping format names to TableFormat specifications
79
80
This design enables extensible formatting through custom TableFormat objects while providing many built-in formats for common output targets.
81
82
## Capabilities
83
84
### Main Tabulation Function
85
86
The primary function for formatting tabular data with comprehensive options for data types, alignment, formatting, and output styles.
87
88
```python { .api }
89
def tabulate(
90
tabular_data,
91
headers=(),
92
tablefmt="simple",
93
floatfmt="g",
94
intfmt="",
95
numalign="default",
96
stralign="default",
97
missingval="",
98
showindex="default",
99
disable_numparse=False,
100
colalign=None,
101
maxcolwidths=None,
102
rowalign=None,
103
maxheadercolwidths=None
104
):
105
"""
106
Format tabular data into a pretty-printed table.
107
108
Args:
109
tabular_data: Input data - list of lists, dict of iterables, pandas DataFrame,
110
list of dicts, list of dataclasses, NumPy arrays, etc.
111
headers (tuple): Column headers - list, "firstrow", "keys", or empty tuple
112
tablefmt (str): Output format - see tabulate_formats for options
113
floatfmt (str): Float formatting specification or list per column
114
intfmt (str): Integer formatting specification or list per column
115
numalign (str): Numeric alignment - "left", "right", "center", "decimal", "default"
116
stralign (str): String alignment - "left", "right", "center", "default"
117
missingval (str): Replacement for None values
118
showindex (str/bool): Row index display - "default", "always", "never", True, False, or iterable
119
disable_numparse (bool): Disable automatic number parsing
120
colalign (list): Per-column alignment override
121
maxcolwidths (list/int): Maximum column widths
122
rowalign (str/list): Row-wise alignment options
123
maxheadercolwidths (list/int): Maximum header column widths
124
125
Returns:
126
str: Formatted table as string
127
"""
128
```
129
130
### Format Utilities
131
132
Access to available output formats and custom format creation.
133
134
```python { .api }
135
# List of all supported output formats
136
tabulate_formats: list[str]
137
138
def simple_separated_format(separator):
139
"""
140
Create a custom TableFormat with columns separated by a separator.
141
142
Args:
143
separator (str): String separator between columns
144
145
Returns:
146
TableFormat: Custom format object for use with tablefmt parameter
147
"""
148
```
149
150
### Constants and Configuration
151
152
Runtime constants affecting table formatting behavior.
153
154
```python { .api }
155
# Special marker for separating lines in table data (unprintable character)
156
SEPARATING_LINE: str = "\001"
157
158
# Minimum extra space in headers
159
MIN_PADDING: int = 2
160
161
# Whether to preserve leading/trailing whitespace in data
162
PRESERVE_WHITESPACE: bool = False
163
164
# Whether wide-character (CJK) support is enabled (depends on wcwidth)
165
WIDE_CHARS_MODE: bool
166
```
167
168
### Data Structures
169
170
Core data structures for custom table formatting.
171
172
```python { .api }
173
class Line:
174
"""Represents table line formatting (namedtuple)."""
175
begin: str # Line beginning character(s)
176
hline: str # Horizontal line character(s)
177
sep: str # Column separator character(s)
178
end: str # Line ending character(s)
179
180
class DataRow:
181
"""Represents table row formatting (namedtuple)."""
182
begin: str # Row beginning character(s)
183
sep: str # Column separator character(s)
184
end: str # Row ending character(s)
185
186
class TableFormat:
187
"""Complete table format specification (namedtuple)."""
188
lineabove: Line | None # Line above table
189
linebelowheader: Line | None # Line below header row
190
linebetweenrows: Line | None # Line between data rows
191
linebelow: Line | None # Line below table
192
headerrow: DataRow | None # Header row format
193
datarow: DataRow | None # Data row format
194
padding: int # Padding around cell content
195
with_header_hide: list | None # Elements to hide when headers present
196
```
197
198
## Supported Input Data Types
199
200
Tabulate accepts various tabular data formats:
201
202
1. **List of lists** - `[[row1_col1, row1_col2], [row2_col1, row2_col2]]`
203
2. **List of dictionaries** - `[{"col1": val1, "col2": val2}, ...]` (dict keys as columns)
204
3. **Dictionary of iterables** - `{"col1": [val1, val2], "col2": [val3, val4]}` (dict keys as columns)
205
4. **List of dataclasses** - Python 3.7+ (field names as columns)
206
5. **Two-dimensional NumPy arrays**
207
6. **NumPy record arrays** - (record names as columns)
208
7. **pandas DataFrame**
209
210
## Supported Output Formats
211
212
Available formats accessible via `tabulate_formats`:
213
214
- **Plain text**: `"plain"`, `"simple"`
215
- **Grid formats**: `"grid"`, `"fancy_grid"`, `"rounded_grid"`, `"simple_grid"`, `"double_grid"`, `"heavy_grid"`, `"mixed_grid"`
216
- **Outline formats**: `"outline"`, `"fancy_outline"`, `"rounded_outline"`, `"simple_outline"`, `"double_outline"`, `"heavy_outline"`, `"mixed_outline"`
217
- **Markup**: `"pipe"` (Markdown), `"github"` (GitHub-flavored Markdown), `"html"`, `"unsafehtml"`
218
- **LaTeX**: `"latex"`, `"latex_raw"`, `"latex_booktabs"`, `"latex_longtable"`
219
- **Wiki/Documentation**: `"mediawiki"`, `"moinmoin"`, `"rst"`, `"textile"`, `"asciidoc"`
220
- **Development**: `"orgtbl"` (Org-mode), `"jira"`, `"presto"`, `"psql"`, `"youtrack"`, `"pretty"`
221
- **Data**: `"tsv"` (tab-separated)
222
223
## Command Line Interface
224
225
Tabulate includes a command-line utility for processing files:
226
227
```bash
228
# Basic usage
229
tabulate data.csv
230
231
# With options
232
tabulate -f grid -1 --float .2f data.csv
233
234
# From stdin
235
cat data.txt | tabulate -f html > output.html
236
```
237
238
Available CLI options:
239
- `-h, --help`: Show help message
240
- `-f, --format FMT`: Set output table format
241
- `-1, --header`: Use first row as header
242
- `-o FILE, --output FILE`: Output to file
243
- `-s REGEXP, --sep REGEXP`: Custom column separator
244
- `-F FPFMT, --float FPFMT`: Float number format
245
- `-I INTFMT, --int INTFMT`: Integer number format
246
- `-C, --colalign`: Column alignment specification
247
248
## Advanced Usage Examples
249
250
### Custom Formatting
251
252
```python
253
from tabulate import tabulate, simple_separated_format
254
255
# Custom separator format
256
tsv_format = simple_separated_format("\\t")
257
result = tabulate(data, tablefmt=tsv_format)
258
259
# Custom number formatting per column
260
result = tabulate(
261
data,
262
floatfmt=[".2f", ".4f"], # Different formats per column
263
intfmt=["d", "04d"] # Different int formats per column
264
)
265
266
# Alignment control
267
result = tabulate(
268
data,
269
numalign="decimal", # Align numbers by decimal point
270
stralign="center", # Center string columns
271
colalign=["left", "right", "center"] # Per-column override
272
)
273
```
274
275
### Working with Different Data Sources
276
277
```python
278
import pandas as pd
279
import numpy as np
280
281
# From pandas DataFrame
282
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
283
print(tabulate(df, headers="keys", tablefmt="grid"))
284
285
# From NumPy array
286
arr = np.array([[1, 2, 3], [4, 5, 6]])
287
print(tabulate(arr, headers=["X", "Y", "Z"]))
288
289
# From list of dictionaries
290
data = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
291
print(tabulate(data, headers="keys"))
292
```
293
294
### Separating Lines and Row Indices
295
296
```python
297
from tabulate import tabulate, SEPARATING_LINE
298
299
# Add separating lines between data sections
300
data = [
301
["Group A", "", ""],
302
["Alice", "Engineer", 75000],
303
["Bob", "Designer", 65000],
304
[SEPARATING_LINE], # Separating line
305
["Group B", "", ""],
306
["Carol", "Manager", 85000],
307
["Dave", "Analyst", 55000]
308
]
309
310
print(tabulate(data, headers=["Name", "Role", "Salary"], tablefmt="grid"))
311
312
# Show row indices
313
print(tabulate(data, showindex="always"))
314
print(tabulate(data, showindex=["Row1", "Row2", "Row3"])) # Custom indices
315
```
316
317
## Error Handling
318
319
Common exceptions that may be raised:
320
321
- **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
322
- **ImportError**: Optional dependencies (wcwidth) not available - gracefully handled internally
323
- **TypeError/UnicodeDecodeError**: Data conversion issues - handled internally with fallbacks