Python

Word-Safe Truncate

admin by @admin ADMIN
3d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Cap a string at `max_len` chars without splitting a word; append an ellipsis when truncated. Backs off to the last space if cutting mid-word would happen.
Python
Raw
def truncate_words(text: str, max_len: int, ellipsis: str = "…") -> str:
    text = text.strip()
    if len(text) <= max_len:
        return text
    budget = max_len - len(ellipsis)
    if budget <= 0:
        return ellipsis[:max_len]
    cut = text[:budget]
    last_space = cut.rfind(" ")
    if last_space > budget * 0.5:
        cut = cut[:last_space]
    return cut.rstrip(" ,.;:") + ellipsis

truncate_words("The quick brown fox jumps over the lazy dog", 20)
# 'The quick brown fox…'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.