Table formatting involves transforming raw data into visually appealing and readable presentations. Python offers multiple techniques to achieve professional table outputs.
## Using format() method
data = [
["Alice", 28, 75000],
["Bob", 35, 85000],
["Charlie", 42, 95000]
]
print("{:<10} {:<5} {:<10}".format("Name", "Age", "Salary"))
print("-" * 30)
for row in data:
print("{:<10} {:<5} ${:<10}".format(*row))
2. Alignment and Padding Techniques
## Right, left, and center alignment
print("{:>10} {:<10} {:^10}".format("Right", "Left", "Center"))
Tabulate Library Advanced Usage
from tabulate import tabulate
data = [
["Alice", 28, 75000],
["Bob", 35, 85000],
["Charlie", 42, 95000]
]
## Multiple formatting styles
print(tabulate(data,
headers=["Name", "Age", "Salary"],
tablefmt="pipe"
))
Technique |
Pros |
Cons |
String Format |
Lightweight |
Limited styling |
Tabulate |
Rich formatting |
Additional dependency |
Pandas |
Data manipulation |
Overhead for simple tables |
graph TD
A[Raw Data] --> B[Choose Formatting Method]
B --> C[Select Alignment]
C --> D[Apply Styling]
D --> E[Render Table]
Color and Styling Techniques
from termcolor import colored
def color_format_table(data):
headers = ["Name", "Status"]
for row in data:
name, status = row
color = 'green' if status == 'Active' else 'red'
print(colored(f"{name:<10} {status:<10}", color))
data = [
["Alice", "Active"],
["Bob", "Inactive"]
]
color_format_table(data)
- Use efficient formatting methods
- Minimize string manipulations
- Choose appropriate libraries for dataset size
Best Practices in LabEx Data Presentation
- Prioritize readability
- Maintain consistent formatting
- Choose appropriate styling for context
- Consider data complexity
By mastering these formatting techniques, developers can create professional and engaging table outputs in Python, enhancing data visualization in LabEx projects.