Creating Tables with PrettyTable Library - Python

Creating Tables with PrettyTable Library - Python

The PrettyTable library in Python allows you to display data in a table format in the console. It provides many customization options for table creation and formatting.

Here's a step-by-step guide to create tables using the PrettyTable library:

1. Install the PrettyTable library:

pip install prettytable 

2. Create a basic table:

from prettytable import PrettyTable # Create a new table table = PrettyTable() # Set column names table.field_names = ["Name", "Age", "City"] # Add rows table.add_row(["Alice", 28, "New York"]) table.add_row(["Bob", 22, "Los Angeles"]) table.add_row(["Charlie", 30, "Chicago"]) print(table) 

3. Customizing the table:

a. Changing column alignments:

table.align["Name"] = "l" # Left align table.align["Age"] = "c" # Center align table.align["City"] = "r" # Right align 

b. Sorting by a column:

table.sortby = "Age" 

c. Adding a title:

table.title = "Sample Table" 

d. Changing horizontal/vertical table rules:

table.hrules = True # Add horizontal rules between rows table.vrules = True # Add vertical rules between columns 

e. Changing table styles:

You can change the table's junction character style using:

table.junction_char = "*" 

4. Print the table:

Finally, print the table:

print(table) 

The PrettyTable library offers even more customization options, such as setting column widths, adding row/column colors, and more. You can explore the library's documentation and source code for a complete list of features and capabilities.


More Tags

neo4j google-drive-api countvectorizer sqoop submenu dynamic-jasper mongotemplate hosts mozilla assertion

More Programming Guides

Other Guides

More Programming Examples