Skip to content

Instantly share code, notes, and snippets.

@un33k
Last active December 13, 2015 17:08
Show Gist options
  • Save un33k/4945249 to your computer and use it in GitHub Desktop.
Save un33k/4945249 to your computer and use it in GitHub Desktop.
def smart_truncate(text, max_length=0, word_boundary=False):
if not max_length or len(text) < max_length:
return text
if not word_boundary:
return text[:max_length].strip('-')
truncated = ''
for i, word in enumerate(text.split('-')):
if not word: continue
if len(truncated) + len(word) + i <= max_length:
truncated += '{0}{1}'.format('-' if i else '', word)
return truncated.strip('-')
if __name__ == '__main__':
for i in range(21):
print smart_truncate('jaja---lol-mememeoo--a', max_length=i, word_boundary=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment