I am looking for a way to truncate a string in Python that will not cut off the string in the middle of a word.
For example:
Original: \"This is
From Python 3.4+ you can use textwrap.shorten. With the OP example:
>>> import textwrap
>>> original = "This is really awesome."
>>> textwrap.shorten(original, width=20, placeholder="...")
'This is really...'
textwrap.shorten(text, width, **kwargs)
Collapse and truncate the given text to fit in the given width.
First the whitespace in text is collapsed (all whitespace is replaced by single spaces). If the result fits in the width, it is returned. Otherwise, enough words are dropped from the end so that the remaining words plus the placeholder fit within width: