Practical Examples
Real-World Alignment Scenarios
1. Creating Tabular Output
def print_student_report():
print("Name".ljust(15) + "Score".rjust(10) + "Grade".rjust(10))
print("-" * 35)
print("John Doe".ljust(15) + "85".rjust(10) + "A".rjust(10))
print("Jane Smith".ljust(15) + "92".rjust(10) + "A+".rjust(10))
def format_financial_data(transactions):
print("Date".ljust(12) + "Description".ljust(20) + "Amount".rjust(10))
for date, desc, amount in transactions:
print(f"{date.ljust(12)}{desc.ljust(20)}{str(amount).rjust(10)}")
Alignment in Data Processing
def format_scientific_data(measurements):
headers = ["Experiment", "Value", "Uncertainty"]
print(f"{headers[0]:^15}{headers[1]:^15}{headers[2]:^15}")
for exp, value, uncertainty in measurements:
print(f"{exp:^15}{value:^15.2f}{uncertainty:^15.3f}")
Complex Alignment Workflow
graph TD
A[Raw Data] --> B[Determine Alignment]
B --> C{Data Type}
C -->|Numeric| D[Right Align]
C -->|Text| E[Left/Center Align]
D --> F[Apply Formatting]
E --> F
F --> G[Formatted Output]
Logging and Debugging Alignment
def create_debug_log(log_entries):
print("Timestamp".ljust(25) + "Level".center(10) + "Message".rjust(30))
print("-" * 65)
for timestamp, level, message in log_entries:
print(f"{timestamp.ljust(25)}{level.center(10)}{message.rjust(30)}")
Alignment Techniques Comparison
Scenario |
Best Method |
Complexity |
Performance |
Simple Text |
ljust() /rjust() |
Low |
High |
Numeric Data |
format() |
Medium |
Medium |
Complex Formatting |
f-strings |
High |
High |
LabEx Advanced Tip
Combine multiple alignment techniques to create sophisticated text layouts:
def advanced_report_generator(data):
for item in data:
formatted = f"{item['name']:^20}{item['value']:>10.2f}{item['status']:^15}"
print(formatted)
## Efficient multi-column alignment
def optimized_alignment(data_list):
return [f"{str(item):^10}" for item in data_list]