Practical Width Handling
Real-world String Width Management
Text Alignment and Formatting
def format_table_row(text, width=20, align='left'):
"""Create aligned text with consistent width"""
if align == 'left':
return text.ljust(width)
elif align == 'right':
return text.rjust(width)
elif align == 'center':
return text.center(width)
## Usage example
print(format_table_row('LabEx', width=10, align='center'))
print(format_table_row('Python', width=10, align='right'))
Width-aware Text Truncation
import unicodedata
def truncate_text(text, max_width):
"""Truncate text while respecting character widths"""
current_width = 0
truncated = []
for char in text:
char_width = 2 if unicodedata.east_asian_width(char) in 'FW' else 1
if current_width + char_width > max_width:
break
truncated.append(char)
current_width += char_width
return ''.join(truncated)
## Demonstration
print(truncate_text('PythonäļææĩčŊ', max_width=10))
Width Handling Workflow
graph TD
A[Input Text] --> B{Calculate Width}
B --> |Width > Limit| C[Truncate]
B --> |Width <= Limit| D[Display]
C --> E[Adjusted Text]
Width Handling Strategies
Strategy |
Use Case |
Complexity |
Truncation |
Limited display space |
Medium |
Wrapping |
Multi-line text |
High |
Scaling |
Dynamic formatting |
Complex |
def print_fixed_width(text, width=30, fill_char='-'):
"""Print text with fixed-width formatting"""
print(text.center(width, fill_char))
## Console output example
print_fixed_width('LabEx Python Tutorial')
Advanced Width Manipulation
def smart_text_pad(text, total_width, pad_char=' '):
"""Intelligently pad text considering character widths"""
current_width = sum(2 if unicodedata.east_asian_width(c) in 'FW' else 1 for c in text)
padding_needed = max(0, total_width - current_width)
return text + pad_char * padding_needed
## Usage
print(smart_text_pad('Python', total_width=10))
print(smart_text_pad('äļæ', total_width=10))
Key Takeaways for Developers
Effective width handling requires:
- Understanding character complexity
- Choosing appropriate calculation methods
- Implementing flexible formatting strategies
By mastering these techniques, LabEx developers can create robust text processing solutions that work across different languages and display environments.