__init___1.py 819 B

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