Last active
December 13, 2015 17:08
-
-
Save un33k/4945249 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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