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
def smart_truncate(s, width):
if s[width].isspace():
return s[0:width];
else:
return s[0:width].rsplit(None, 1)[0]
Testing it:
>>> smart_truncate('The quick brown fox jumped over the lazy dog.', 23) + "..."
'The quick brown fox...'
For Python 3.4+, I'd use textwrap.shorten.
For older versions:
def truncate(description, max_len=140, suffix='…'):
description = description.strip()
if len(description) <= max_len:
return description
new_description = ''
for word in description.split(' '):
tmp_description = new_description + word
if len(tmp_description) <= max_len-len(suffix):
new_description = tmp_description + ' '
else:
new_description = new_description.strip() + suffix
break
return new_description