__init__.py 918 B

12345678910111213141516171819202122232425262728
  1. # -*- coding: utf-8 -*-
  2. try:
  3. basestring
  4. except NameError: # Python 3
  5. basestring = str
  6. def truncate(text, length, ellipsis='...'):
  7. """Truncate `text` to `length`, add `ellipsis` if needed."""
  8. if text is None:
  9. text = ''
  10. if not isinstance(text, basestring):
  11. raise ValueError("%r is no instance of basestring or None" % text)
  12. # thread other whitespaces as word break
  13. content = text.replace('\r', ' ').replace('\n', ' ').replace('\t', ' ')
  14. # make sure to have at least one space for finding spaces later on
  15. content += ' '
  16. if len(content) > length:
  17. # find the next space after max_len chars (do not break inside a word)
  18. pos = length + content[length:].find(' ')
  19. if pos != (len(content) - 1):
  20. # if the found whitespace is not the last one add an ellipsis
  21. text = text[:pos].strip() + ' ' + ellipsis
  22. return text