Now that you have learned different alignment techniques, let's apply them to create well-formatted tables. Tables are a common way to display structured data in a readable format, and proper alignment is crucial for presenting tabular information effectively.
Simple Table with Fixed Width Columns
Let's start by creating a simple table using fixed width columns.
- Create a new file named
simple_table.py in the /home/labex/project directory:
## simple_table.py
print("Simple Fixed-Width Table")
print("-" * 50)
## Define some data
header = ["Name", "Age", "City", "Profession"]
data = [
["John Smith", 34, "New York", "Doctor"],
["Sarah Johnson", 28, "San Francisco", "Engineer"],
["Michael Brown", 42, "Chicago", "Teacher"],
["Emily Davis", 31, "Boston", "Scientist"]
]
## Print header
print(f"{header[0]:<20} {header[1]:<8} {header[2]:<15} {header[3]:<15}")
print("-" * 60)
## Print rows
for row in data:
print(f"{row[0]:<20} {row[1]:<8} {row[2]:<15} {row[3]:<15}")
- Save the file and run it:
python3 ~/project/simple_table.py
- You should see a neatly formatted table like this:
Simple Fixed-Width Table
--------------------------------------------------
Name Age City Profession
------------------------------------------------------------
John Smith 34 New York Doctor
Sarah Johnson 28 San Francisco Engineer
Michael Brown 42 Chicago Teacher
Emily Davis 31 Boston Scientist
Dynamic Table with Multiple Alignment Types
Different types of data often look better with different alignment styles. For example, text is often left-aligned, while numbers are right-aligned. Let's create a more sophisticated table with mixed alignment.
- Create a new file named
dynamic_table.py in the /home/labex/project directory:
## dynamic_table.py
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Calculate column widths based on content
col_widths = [
max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]
## Print header
print(f"{header[0]:<{col_widths[0]}}"
f"{header[1]:>{col_widths[1]}}"
f"{header[2]:>{col_widths[2]}}"
f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{col_widths[0]}}",
f"${product[1]:.2f}".rjust(col_widths[1]),
f"{product[2]}".rjust(col_widths[2]),
f"${product[3]:.2f}".rjust(col_widths[3]))
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}",
f"".rjust(col_widths[1]),
f"{total_quantity}".rjust(col_widths[2]),
f"${total_cost:.2f}".rjust(col_widths[3]))
- This code has an error that we need to fix. The formatting for the price and total columns is incorrect. Let's correct it:
## dynamic_table.py - corrected version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Calculate column widths based on content
col_widths = [
max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]
## Print header
print(f"{header[0]:<{col_widths[0]}}"
f"{header[1]:>{col_widths[1]}}"
f"{header[2]:>{col_widths[2]}}"
f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{col_widths[0]}}",
f"${product[1]:.2f}".rjust(col_widths[1]),
f"{product[2]}".rjust(col_widths[2]),
f"${product[3]:.2f}".rjust(col_widths[3]))
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}",
f"".rjust(col_widths[1]),
f"{total_quantity}".rjust(col_widths[2]),
f"${total_cost:.2f}".rjust(col_widths[3]))
- Save the corrected file and run it:
python3 ~/project/dynamic_table.py
- Let's simplify this example to make it more robust and easier to understand for beginners:
## dynamic_table.py - simplified version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price ($)", "Quantity", "Total ($)"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Fixed column widths
product_width = 15
price_width = 12
quantity_width = 10
total_width = 12
## Print header
print(f"{header[0]:<{product_width}}"
f"{header[1]:>{price_width}}"
f"{header[2]:>{quantity_width}}"
f"{header[3]:>{total_width}}")
print("-" * (product_width + price_width + quantity_width + total_width))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{product_width}}"
f"{product[1]:>{price_width}.2f}"
f"{product[2]:>{quantity_width}}"
f"{product[3]:>{total_width}.2f}")
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * (product_width + price_width + quantity_width + total_width))
print(f"{'TOTAL':<{product_width}}"
f"{'':{price_width}}"
f"{total_quantity:>{quantity_width}}"
f"{total_cost:>{total_width}.2f}")
- Save this simplified version over the previous file and run it:
python3 ~/project/dynamic_table.py
- You should see a well-formatted table like this:
Dynamic Table with Mixed Alignment
--------------------------------------------------
Product Price ($) Quantity Total ($)
-------------------------------------------------------
Laptop 1299.99 3 3899.97
Mouse 24.50 10 245.00
Monitor 349.95 2 699.90
Keyboard 49.99 5 249.95
Headphones 89.95 4 359.80
-------------------------------------------------------
TOTAL 24 5454.62
Creating a Financial Report
Now, let's create a more practical example - a financial report that uses alignment techniques for better readability.
- Create a new file named
financial_report.py in the /home/labex/project directory:
## financial_report.py
print("Monthly Financial Report")
print("=" * 60)
## Financial data
income_sources = [
["Salary", 5000.00],
["Freelance Work", 1200.50],
["Investments", 450.75],
["Other Income", 300.00]
]
expenses = [
["Rent", 1500.00],
["Utilities", 250.30],
["Groceries", 600.45],
["Transportation", 200.00],
["Insurance", 300.00],
["Entertainment", 150.25],
["Savings", 800.00],
["Miscellaneous", 300.00]
]
## Print Income Section
print("\nINCOME STATEMENT")
print("-" * 40)
print(f"{'Source':<20}{'Amount ($)':>20}")
print("-" * 40)
total_income = 0
for source, amount in income_sources:
total_income += amount
print(f"{source:<20}{amount:>20.2f}")
print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print()
## Print Expense Section
print("\nEXPENSE STATEMENT")
print("-" * 40)
print(f"{'Category':<20}{'Amount ($)':>20}")
print("-" * 40)
total_expenses = 0
for category, amount in expenses:
total_expenses += amount
print(f"{category:<20}{amount:>20.2f}")
print("-" * 40)
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print()
## Print Summary
print("\nMONTHLY SUMMARY")
print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print("-" * 40)
balance = total_income - total_expenses
print(f"{'Net Balance':<20}{balance:>20.2f}")
## Add some conditional formatting for the balance
if balance > 0:
print(f"\nStatus: You saved ${balance:.2f} this month!")
else:
print(f"\nStatus: You overspent by ${-balance:.2f} this month.")
- Save the file and run it:
python3 ~/project/financial_report.py
- You should see a comprehensive financial report with nicely aligned columns:
Monthly Financial Report
============================================================
INCOME STATEMENT
----------------------------------------
Source Amount ($)
----------------------------------------
Salary 5000.00
Freelance Work 1200.50
Investments 450.75
Other Income 300.00
----------------------------------------
Total Income 6951.25
EXPENSE STATEMENT
----------------------------------------
Category Amount ($)
----------------------------------------
Rent 1500.00
Utilities 250.30
Groceries 600.45
Transportation 200.00
Insurance 300.00
Entertainment 150.25
Savings 800.00
Miscellaneous 300.00
----------------------------------------
Total Expenses 4101.00
MONTHLY SUMMARY
----------------------------------------
Total Income 6951.25
Total Expenses 4101.00
----------------------------------------
Net Balance 2850.25
Status: You saved $2850.25 this month!
This example shows how proper alignment can make complex financial information much easier to read and understand.
Key Takeaways
Through these examples, you've learned how to:
- Create simple fixed-width tables with consistent alignment
- Apply different alignment types based on data types (left for text, right for numbers)
- Create practical, real-world reports with clear visual organization
- Use string formatting methods to achieve precise control over output
These skills are valuable not just for console output but can be applied when generating reports, creating log files, or presenting data in any text-based format.