Truncate Multiline Text with Smart Ellipsis
Blindly chopping strings at exact character offsets splits words awkwardly like `"produc..."`. A smart truncation utility collapses multiline whitespace, finds the closest natural word boundary before the character ceiling, strips dangling punctuation, and appends a clean ellipsis ✂️📄⚡.
import re
def truncate_text(text, limit=20, mark="..."):
normalized = re.sub(r"\s+", " ", text).strip()
if len(normalized) <= limit: return normalized
cutoff = limit - len(mark)
idx = normalized.rfind(" ", 0, cutoff + 1)
chunk = normalized[:idx if idx != -1 else cutoff].rstrip(",.!? ")
return chunk + mark
raw = "Engine metrics need high-performance telemetry sinks."
print("Truncated:", truncate_text(raw, limit=22))
# 4. Truncate Multiline Text with Smart Ellipsis Displaying arbitrary database records or log messages in compact UI lists or CLI tables frequently results in unsightly wrapping or ugly mid-word truncation like `"Database connection pool exhau..."` 🛑. ```python # The Truncation Problem: # Naive Slice (limit=20): "System crashed unexpectedly" -> "System crashed unex..." (Messy!) # Smart Word-Aware Slice: "System crashed unexpectedly" -> "System crashed..." (Clean!) ``` ### Engineering Requirements for Clean Previews 1. **Whitespace Normalization**: Convert tabs, carriage returns, and multiple spaces into single spaces before measuring length. 2. **Word-Boundary Awareness**: Use `rfind(' ', 0, cutoff)` to step back to the nearest space instead of amputating letters mid-word. 3. **Punctuation Trimming**: Never output an ellipsis immediately following a comma, period, or space (`"Database, ..."` looks amateurish). Strip trailing punctuation before attaching `...` ✂️📄⚡. --- ### Interactive Pop-Quiz 🧠 #### Why must text truncation collapse consecutive whitespace characters and newlines before calculating offsets? - [ ] Multiple spaces, tabs, and newlines skew character counts without adding visual information in compact single-line UI views ✂️ - [ ] Because Python strings reject newlines during slicing - [ ] To force the terminal to render monospace fonts - [ ] Whitespace characters cause CPU memory fragmentation --- ### Practical Challenge 🎯 Implement `smart_truncate(text: str, max_length: int = 25, ellipsis: str = '...') -> str`. Collapse all whitespace and newlines to a single space. If length is within `max_length`, return as-is. Otherwise find the last space at or before `max_length - len(ellipsis)`, trim trailing spaces and punctuation (`,.!?`), and append the ellipsis. Test with `'Production databases require strict resilience and continuous telemetry.'` at limit 25, assert `'Production databases...'`, and print result. <details> <summary>Solution</summary> ```python import re def smart_truncate(text: str, max_length: int = 25, ellipsis: str = "...") -> str: clean = re.sub(r"\s+", " ", text).strip() if len(clean) <= max_length: return clean cutoff = max_length - len(ellipsis) space_idx = clean.rfind(" ", 0, cutoff + 1) if space_idx != -1: truncated = clean[:space_idx] else: truncated = clean[:cutoff] truncated = truncated.rstrip(",.!? \t") return truncated + ellipsis src = "Production databases require strict resilience and continuous telemetry." res = smart_truncate(src, max_length=25) assert len(res) <= 25 assert res == "Production databases..." print(f"Smart truncate verified: '{res}' (len={len(res)})") ``` </details>