Custom Padding Techniques
Advanced String Padding Strategies
1. Flexible Padding Function
def custom_pad(text, width, pad_char=' ', align='left'):
"""
Flexible string padding with multiple alignment options
:param text: Input string to pad
:param width: Total width of padded string
:param pad_char: Character used for padding
:param align: Alignment type (left, right, center)
:return: Padded string
"""
text = str(text)
if align == 'left':
return text.ljust(width, pad_char)
elif align == 'right':
return text.rjust(width, pad_char)
elif align == 'center':
return text.center(width, pad_char)
else:
raise ValueError("Invalid alignment type")
## Usage examples
print(custom_pad("LabEx", 10, '-', 'center'))
print(custom_pad(42, 8, '0', 'right'))
Padding Techniques Workflow
graph TD
A[Input String] --> B{Padding Strategy}
B --> |Left Align| C[Left Padding]
B --> |Right Align| D[Right Padding]
B --> |Center Align| E[Center Padding]
B --> |Conditional| F[Custom Logic]
Complex Padding Scenarios
2. Conditional Padding
def smart_pad(data, config):
"""
Intelligent padding based on configuration
:param data: Input data to pad
:param config: Padding configuration dictionary
:return: Padded string
"""
result = str(data)
## Apply type-specific padding
if isinstance(data, int):
result = result.zfill(config.get('width', len(result)))
elif isinstance(data, str):
result = result.ljust(config.get('width', len(result)),
config.get('pad_char', ' '))
return result
## Configuration examples
configs = [
{'width': 10, 'pad_char': '-'},
{'width': 8, 'pad_char': '0'}
]
## Demonstrate smart padding
print(smart_pad(42, configs[0]))
print(smart_pad("LabEx", configs[1]))
Padding Techniques Comparison
Technique |
Flexibility |
Use Case |
Performance |
Built-in Methods |
Low |
Simple Padding |
High |
Custom Function |
Medium |
Moderate Complexity |
Good |
Advanced Conditional |
High |
Complex Scenarios |
Moderate |
def optimized_pad(text, width, pad_char=' '):
"""
Memory-efficient padding technique
"""
text_len = len(text)
if text_len >= width:
return text[:width]
padding_needed = width - text_len
left_pad = padding_needed // 2
right_pad = padding_needed - left_pad
return (pad_char * left_pad) + text + (pad_char * right_pad)
## Performance examples
print(optimized_pad("LabEx", 10))
print(optimized_pad("Python", 8, '-'))
Best Practices
- Choose padding technique based on specific requirements
- Consider performance implications
- Implement error handling
- Use type checking for robust padding
- Optimize for memory and computational efficiency
Error Handling and Validation
def robust_pad(text, width, pad_char=' ', align='left'):
try:
## Validate input parameters
if not isinstance(width, int) or width < 0:
raise ValueError("Width must be a non-negative integer")
## Apply padding with error handling
if align == 'left':
return str(text).ljust(width, pad_char)
elif align == 'right':
return str(text).rjust(width, pad_char)
elif align == 'center':
return str(text).center(width, pad_char)
else:
raise ValueError("Invalid alignment type")
except Exception as e:
print(f"Padding error: {e}")
return str(text)
## Demonstrate robust padding
print(robust_pad("LabEx", 10, '-'))