There is an excellent discussion here Truncate a string without ending in the middle of a word on how to do a 'smart' string truncation in python. But the problem with the solutions proposed there is that if the width limit falls within a word, then this word is thrown off completely.
How can I truncate a string in python setting a 'soft' width limit, i.e. if the limit falls in the middle of the word, then this word is kept?
Example:
str = "it's always sunny in philadelphia"
trunc(str, 7)
>>> it's always...
My initial thinking is to slice the string up to the soft limit and then start checking every next character, adding it to the slice until I encounter a whitespace character. But this seems extremely inefficient.