Practical Centering Examples
def print_header(title, width=40):
"""Generate centered console headers"""
print(title.center(width, '-'))
print_header("LabEx Python Tutorial")
print_header("Data Processing", 50)
Table Generation
def create_centered_table(data):
"""Generate centered table rows"""
for row in data:
centered_row = [str(item).center(15) for item in row]
print(" | ".join(centered_row))
data = [
["Name", "Age", "City"],
["Alice", 28, "New York"],
["Bob", 35, "San Francisco"]
]
create_centered_table(data)
Dynamic Width Calculation
def auto_center_text(texts):
"""Dynamically center texts based on maximum length"""
max_width = max(len(text) for text in texts)
for text in texts:
print(text.center(max_width + 4))
texts = ["Python", "LabEx", "Programming"]
auto_center_text(texts)
Logging and Report Generation
def generate_report_section(title, content):
"""Create centered report sections"""
print(title.center(50, '='))
print(content.center(50))
print('=' * 50)
generate_report_section(
"Monthly Performance",
"Total Efficiency: 95%"
)
Text Alignment Workflow
graph TD
A[Input Text] --> B{Determine Width}
B --> |Calculate| C[Add Padding]
C --> D[Centered Output]
Practical Use Cases
Scenario |
Centering Method |
Use Case |
Console UI |
.center() |
Menu displays |
Logging |
Custom function |
Formatted logs |
Report Generation |
F-strings |
Structured reports |
Data Presentation |
Formatting |
Tabular displays |
Advanced Centering Techniques
def multi_column_center(columns, width=20):
"""Center multiple columns"""
return [col.center(width) for col in columns]
columns = ["Name", "Score", "Rank"]
centered_columns = multi_column_center(columns)
print(" | ".join(centered_columns))
Error Handling
def safe_center(text, width):
"""Safely center strings with error handling"""
try:
return text.center(width) if len(text) <= width else text
except TypeError:
return "Invalid Input"
## Example usage
print(safe_center("Python", 10))
print(safe_center(123, 10)) ## Handles type conversion
def efficient_center(texts, width=30):
"""Efficient centering for multiple texts"""
return [text.center(width) for text in texts]
large_text_list = ["Python", "LabEx", "Programming"] * 1000
centered_texts = efficient_center(large_text_list)