Column formatting is crucial for creating readable and professional data presentations. This section explores advanced techniques to control and customize column displays in Python.
## Advanced f-string formatting
name = "Alice"
salary = 5000.75
print(f"Name: {name:^10} | Salary: ${salary:>10.2f}")
## Using format() with precision and alignment
products = [
("Laptop", 1200.50),
("Smartphone", 800.25),
("Tablet", 450.75)
]
print("Product Pricing Table")
for product, price in products:
print("{:<15} ${:>8.2f}".format(product, price))
Column Width and Precision
import pandas as pd
## Creating a DataFrame with custom formatting
df = pd.DataFrame({
'Name': ['John', 'Emma', 'Michael'],
'Salary': [5000.75, 6200.50, 4800.25]
})
## Set display options
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 100)
pd.set_option('display.float_format', '{:.2f}'.format)
print(df)
Technique |
Pros |
Cons |
f-Strings |
Modern, Readable |
Python 3.6+ only |
.format() |
Flexible |
More verbose |
%-Formatting |
Legacy support |
Less readable |
Alignment and Padding Strategies
graph TD
A[Formatting Technique] --> B{Alignment Type}
B --> |Left Align| C[< Symbol]
B --> |Right Align| D[> Symbol]
B --> |Center Align| E[^ Symbol]
def format_column(data, width=10, align='<', precision=2):
"""
Custom column formatting function
:param data: Data to format
:param width: Column width
:param align: Alignment type
:param precision: Float precision
"""
format_spec = f"{'{'}:{align}{width}.{precision}f{'}'}"
return format_spec.format(data)
## Example usage
print(format_column(5000.7654, width=15, align='^', precision=2))
LabEx Pro Tip
When working with complex column displays, LabEx recommends creating utility functions to standardize formatting across your projects.
- f-Strings are generally faster
- Avoid repeated formatting in loops
- Use vectorized operations with Pandas