# Created on savesnippets.com · https://savesnippets.com/Zo2DY6xegqeQtx 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…'