0
# Core Table Operations
1
2
Core functionality for creating, manipulating, and managing table data. This includes table initialization, row and column operations, data management, and basic table structure operations.
3
4
**Required imports for type annotations:**
5
6
```python
7
from typing import Any
8
from collections.abc import Sequence
9
```
10
11
## Capabilities
12
13
### Table Initialization
14
15
Create new table instances with optional field names and formatting parameters.
16
17
```python { .api }
18
class PrettyTable:
19
def __init__(self, field_names: Sequence[str] | None = None, **kwargs):
20
"""
21
Initialize a new PrettyTable.
22
23
Parameters:
24
- field_names: Sequence of column headers
25
- **kwargs: Formatting options (align, valign, padding_width, etc.)
26
"""
27
```
28
29
Usage example:
30
31
```python
32
# Create empty table
33
table = PrettyTable()
34
35
# Create table with field names
36
table = PrettyTable(["Name", "Age", "City"])
37
38
# Create with formatting options
39
table = PrettyTable(field_names=["Item", "Price"], padding_width=2, align="l")
40
```
41
42
### Row Operations
43
44
Add, remove, and manage table rows with support for dividers and bulk operations.
45
46
```python { .api }
47
def add_row(self, row: list[Any], *, divider: bool = False) -> None:
48
"""
49
Add a single row to the table.
50
51
Parameters:
52
- row: List of values for each column
53
- divider: Whether to add a divider after this row
54
"""
55
56
def add_rows(self, rows: list[list[Any]], *, divider: bool = False) -> None:
57
"""
58
Add multiple rows to the table.
59
60
Parameters:
61
- rows: List of row lists
62
- divider: Whether to add dividers after each row
63
"""
64
65
def del_row(self, row_index: int) -> None:
66
"""
67
Delete a row by index.
68
69
Parameters:
70
- row_index: Zero-based index of row to delete
71
"""
72
73
def add_divider(self) -> None:
74
"""Add a divider after the last row."""
75
```
76
77
Usage examples:
78
79
```python
80
# Add single row
81
table.add_row(["Alice", 25, "New York"])
82
83
# Add row with divider
84
table.add_row(["Bob", 30, "Boston"], divider=True)
85
86
# Add multiple rows
87
table.add_rows([
88
["Charlie", 35, "Chicago"],
89
["Diana", 28, "Denver"]
90
])
91
92
# Delete second row
93
table.del_row(1)
94
95
# Add divider
96
table.add_divider()
97
```
98
99
### Column Operations
100
101
Add, remove, and manage table columns with alignment options.
102
103
```python { .api }
104
def add_column(self, fieldname: str, column: list[Any], align: str = 'c', valign: str = 't') -> None:
105
"""
106
Add a new column to the table.
107
108
Parameters:
109
- fieldname: Name for the column header
110
- column: List of values for the column
111
- align: Column alignment ('l', 'c', 'r')
112
- valign: Vertical alignment ('t', 'm', 'b')
113
"""
114
115
def del_column(self, fieldname: str) -> None:
116
"""
117
Delete a column by field name.
118
119
Parameters:
120
- fieldname: Name of column to delete
121
"""
122
123
def add_autoindex(self, fieldname: str = 'Index') -> None:
124
"""
125
Add an auto-incrementing index column.
126
127
Parameters:
128
- fieldname: Name for the index column
129
"""
130
```
131
132
Usage examples:
133
134
```python
135
# Add column with data
136
table.add_column("Score", [95, 87, 92, 78], align='r')
137
138
# Add auto-incrementing index
139
table.add_autoindex()
140
141
# Delete column
142
table.del_column("Score")
143
```
144
145
### Data Management
146
147
Clear, copy, and manage table data while preserving or modifying structure.
148
149
```python { .api }
150
def clear_rows(self) -> None:
151
"""Remove all rows but keep field names and formatting."""
152
153
def clear(self) -> None:
154
"""Remove all data including field names and reset formatting."""
155
156
def copy(self) -> 'PrettyTable':
157
"""Create a deep copy of the table."""
158
```
159
160
Usage examples:
161
162
```python
163
# Clear all rows but keep headers
164
table.clear_rows()
165
166
# Clear everything
167
table.clear()
168
169
# Create a copy
170
table_copy = table.copy()
171
```
172
173
### Table Properties
174
175
Access and modify table structure and data through properties.
176
177
```python { .api }
178
@property
179
def field_names(self) -> list[str]:
180
"""Get or set column headers."""
181
182
@field_names.setter
183
def field_names(self, value: list[str]) -> None: ...
184
185
@property
186
def rows(self) -> list[list[Any]]:
187
"""Get all data rows."""
188
189
@property
190
def dividers(self) -> list[bool]:
191
"""Get divider positions."""
192
```
193
194
Usage examples:
195
196
```python
197
# Set field names
198
table.field_names = ["Name", "Age", "City"]
199
200
# Get field names
201
headers = table.field_names
202
203
# Access all rows
204
all_data = table.rows
205
206
# Check divider positions
207
divider_list = table.dividers
208
```
209
210
### Style Properties
211
212
Control table appearance through formatting properties.
213
214
```python { .api }
215
@property
216
def align(self) -> dict[str, str]:
217
"""Column alignment settings."""
218
219
@property
220
def valign(self) -> dict[str, str]:
221
"""Vertical alignment settings."""
222
223
@property
224
def title(self) -> str | None:
225
"""Table title."""
226
227
@title.setter
228
def title(self, value: str | None) -> None: ...
229
230
@property
231
def header(self) -> bool:
232
"""Whether to show header row."""
233
234
@header.setter
235
def header(self, value: bool) -> None: ...
236
237
@property
238
def border(self) -> bool:
239
"""Whether to show table border."""
240
241
@border.setter
242
def border(self, value: bool) -> None: ...
243
```
244
245
Usage examples:
246
247
```python
248
# Set column alignment
249
table.align["Name"] = "l"
250
table.align["Age"] = "r"
251
252
# Set table title
253
table.title = "Employee Data"
254
255
# Control header display
256
table.header = True
257
258
# Control border display
259
table.border = False
260
```
261
262
### Style Application
263
264
Apply predefined styles and manage formatting options.
265
266
```python { .api }
267
def set_style(self, style: TableStyle) -> None:
268
"""
269
Apply a predefined table style.
270
271
Parameters:
272
- style: TableStyle enum value
273
"""
274
```
275
276
Usage example:
277
278
```python
279
from prettytable import TableStyle
280
281
# Apply markdown style
282
table.set_style(TableStyle.MARKDOWN)
283
284
# Apply double border style
285
table.set_style(TableStyle.DOUBLE_BORDER)
286
```
287
288
### Dynamic Properties
289
290
Access dynamic table information and advanced formatting properties.
291
292
```python { .api }
293
@property
294
def rowcount(self) -> int:
295
"""Number of data rows in the table (read-only)."""
296
297
@property
298
def colcount(self) -> int:
299
"""Number of columns in the table (read-only)."""
300
301
@property
302
def none_format(self) -> dict[str, str]:
303
"""Format string for None values in each column."""
304
305
@none_format.setter
306
def none_format(self, value: dict[str, str]) -> None: ...
307
308
@property
309
def preserve_internal_border(self) -> bool:
310
"""Whether to preserve internal borders when printing without header."""
311
312
@preserve_internal_border.setter
313
def preserve_internal_border(self, value: bool) -> None: ...
314
315
@property
316
def print_empty(self) -> bool:
317
"""Whether to print table when empty."""
318
319
@print_empty.setter
320
def print_empty(self, value: bool) -> None: ...
321
```
322
323
Usage examples:
324
325
```python
326
# Check table dimensions
327
print(f"Table has {table.rowcount} rows and {table.colcount} columns")
328
329
# Set None value formatting
330
table.none_format["Score"] = "N/A"
331
table.none_format["Name"] = "-"
332
333
# Control empty table printing
334
table.print_empty = False
335
336
# Control internal borders
337
table.preserve_internal_border = True
338
```
339
340
### Special Methods
341
342
Support for advanced table operations and integrations.
343
344
```python { .api }
345
def __getitem__(self, index: slice | int) -> 'PrettyTable':
346
"""
347
Slice table rows to create new table.
348
349
Parameters:
350
- index: Slice object or integer for row selection
351
352
Returns:
353
New PrettyTable containing selected rows
354
"""
355
356
def _repr_html_(self) -> str:
357
"""HTML representation for Jupyter notebook display."""
358
```
359
360
Usage examples:
361
362
```python
363
# Slice table (first 5 rows)
364
first_five = table[:5]
365
366
# Get specific row as single-row table
367
row_table = table[2]
368
369
# Slice with step
370
every_other = table[::2]
371
372
# Jupyter notebook will automatically use _repr_html_
373
# when displaying table in cells
374
table # Displays as HTML table in Jupyter
375
```
376
377
### Additional Output Methods
378
379
Extended output formatting capabilities.
380
381
```python { .api }
382
def get_formatted_string(self, out_format: str, **kwargs) -> str:
383
"""
384
Get table string in specified format.
385
386
Parameters:
387
- out_format: Output format ("csv", "json", "html", "latex", "mediawiki")
388
- **kwargs: Format-specific options
389
390
Returns:
391
Formatted table string
392
"""
393
```
394
395
Usage example:
396
397
```python
398
# Get formatted output
399
csv_output = table.get_formatted_string("csv")
400
json_output = table.get_formatted_string("json")
401
html_output = table.get_formatted_string("html", attributes={"class": "my-table"})
402
```