Nachdem Sie verschiedene Ausrichtungstechniken gelernt haben, wenden wir diese nun an, um gut formatierte Tabellen zu erstellen. Tabellen sind eine gängige Methode, um strukturierte Daten in einem lesbaren Format anzuzeigen, und eine korrekte Ausrichtung ist entscheidend, um tabellarische Informationen effektiv darzustellen.
Einfache Tabelle mit Spalten fester Breite
Beginnen wir mit der Erstellung einer einfachen Tabelle mit Spalten fester Breite.
- Erstellen Sie eine neue Datei namens
simple_table.py
im Verzeichnis /home/labex/project
:
## 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}")
- Speichern Sie die Datei und führen Sie sie aus:
python3 ~/project/simple_table.py
- Sie sollten eine sauber formatierte Tabelle wie diese sehen:
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
Dynamische Tabelle mit mehreren Ausrichtungstypen
Unterschiedliche Datentypen sehen oft besser mit verschiedenen Ausrichtungsstilen aus. Beispielsweise wird Text oft linksbündig ausgerichtet, während Zahlen rechtsbündig ausgerichtet werden. Erstellen wir eine anspruchsvollere Tabelle mit gemischter Ausrichtung.
- Erstellen Sie eine neue Datei namens
dynamic_table.py
im Verzeichnis /home/labex/project
:
## 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}:>{col_widths[1] - 1}"
f"{product[2]:>{col_widths[2]}}"
f"${product[3]:.2f}:>{col_widths[3] - 1}")
## 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"{'':{col_widths[1]}}"
f"{total_quantity:>{col_widths[2]}}"
f"${total_cost:.2f}:>{col_widths[3] - 1}")
- Dieser Code hat einen Fehler, den wir beheben müssen. Die Formatierung für die Spalten "Price" und "Total" ist falsch. Korrigieren wir es:
## 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]))
- Speichern Sie die korrigierte Datei und führen Sie sie aus:
python3 ~/project/dynamic_table.py
- Vereinfachen wir dieses Beispiel, um es robuster und für Anfänger leichter verständlich zu machen:
## 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}")
- Speichern Sie diese vereinfachte Version über die vorherige Datei und führen Sie sie aus:
python3 ~/project/dynamic_table.py
- Sie sollten eine gut formatierte Tabelle wie diese sehen:
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
Erstellen eines Finanzberichts
Jetzt erstellen wir ein praktischeres Beispiel - einen Finanzbericht, der Ausrichtungstechniken für eine bessere Lesbarkeit verwendet.
- Erstellen Sie eine neue Datei namens
financial_report.py
im Verzeichnis /home/labex/project
:
## 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.")
- Speichern Sie die Datei und führen Sie sie aus:
python3 ~/project/financial_report.py
- Sie sollten einen umfassenden Finanzbericht mit schön ausgerichteten Spalten sehen:
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!
Dieses Beispiel zeigt, wie eine korrekte Ausrichtung komplexe Finanzinformationen viel einfacher lesbar und verständlich macht.
Wichtige Erkenntnisse
Durch diese Beispiele haben Sie gelernt, wie Sie:
- Einfache Tabellen mit Spalten fester Breite und konsistenter Ausrichtung erstellen
- Verschiedene Ausrichtungstypen basierend auf Datentypen anwenden (links für Text, rechts für Zahlen)
- Praktische, realweltliche Berichte mit einer klaren visuellen Organisation erstellen
- String-Formatierungsmethoden verwenden, um eine genaue Kontrolle über die Ausgabe zu erreichen
Diese Fähigkeiten sind nicht nur für die Konsolenausgabe wertvoll, sondern können auch bei der Erstellung von Berichten, Log-Dateien oder der Präsentation von Daten in jedem textbasierten Format angewendet werden.