Dynamic Width Calculation
Adaptive Padding Techniques
def dynamic_center(data_list):
max_width = max(len(str(item)) for item in data_list) + 4
return [str(item).center(max_width) for item in data_list]
## Example usage
items = ["Python", "LabEx", "Programming"]
centered_items = dynamic_center(items)
print("\n".join(centered_items))
def create_formatted_table(headers, data):
## Calculate column widths dynamically
col_widths = [max(len(str(row[i])) for row in [headers] + data) + 2
for i in range(len(headers))]
## Print headers
header_row = " | ".join(
header.center(width) for header, width in zip(headers, col_widths)
)
print(header_row)
print("-" * len(header_row))
## Print data rows
for row in data:
formatted_row = " | ".join(
str(cell).center(width) for cell, width in zip(row, col_widths)
)
print(formatted_row)
## Example usage
headers = ["Name", "Language", "Experience"]
data = [
["Alice", "Python", "5 years"],
["Bob", "JavaScript", "3 years"],
["Charlie", "LabEx", "2 years"]
]
create_formatted_table(headers, data)
Smart Padding Strategies
def smart_format(text, width, condition=None):
"""
Conditionally format string with dynamic padding
"""
if condition and not condition(text):
return text.center(width, '!')
return text.center(width)
## Example with length-based formatting
def length_check(s):
return len(s) <= 10
names = ["Python", "LongNameThatExceedsLimit", "LabEx"]
formatted_names = [smart_format(name, 15, length_check) for name in names]
print("\n".join(formatted_names))
Efficient Padding Techniques
import timeit
def method_center(text, width):
return text.center(width)
def method_format(text, width):
return f"{text:^{width}}"
def method_ljust_rjust(text, width):
padding = width - len(text)
left_pad = padding // 2
right_pad = padding - left_pad
return " " * left_pad + text + " " * right_pad
## Performance comparison
text = "LabEx"
width = 10
print("center() method:",
timeit.timeit(lambda: method_center(text, width), number=10000))
print("f-string method:",
timeit.timeit(lambda: method_format(text, width), number=10000))
print("manual padding method:",
timeit.timeit(lambda: method_ljust_rjust(text, width), number=10000))
graph TD
A[Input String] --> B{Formatting Decision}
B --> |Fixed Width| C[Standard Centering]
B --> |Dynamic Width| D[Adaptive Padding]
B --> |Conditional| E[Smart Formatting]
C --> F[Formatted Output]
D --> F
E --> F
Best Practices
Technique |
Use Case |
Complexity |
center() |
Simple centering |
Low |
f-string |
Flexible formatting |
Medium |
Custom function |
Complex scenarios |
High |
Key Takeaways
- Choose the right method based on specific requirements
- Consider performance for large-scale formatting
- Implement custom logic when standard methods are insufficient
- Always validate input and handle edge cases