README.rst 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. Nicely truncate text
  2. ====================
  3. Intelligent truncation of text means that truncation does not take
  4. place inside a word but only between words. So the required length is
  5. only an approximation. The result text might be a bit longer than the
  6. required length:
  7. >>> from icemac.truncatetext import truncate
  8. >>> 'I was here.'[:3]
  9. 'I w'
  10. >>> truncate('I was here.', 3)
  11. 'I was ...'
  12. What can get truncated?
  13. -----------------------
  14. Only instances of ``basestring`` (``str`` on Python 3) can be truncated:
  15. >>> truncate(3, 3)
  16. Traceback (most recent call last):
  17. ValueError: 3 is no instance of basestring or None
  18. >>> print(truncate(u'Lorem ipsum', 5))
  19. Lorem ...
  20. ``None`` is handled nicely:
  21. >>> truncate(None, 4)
  22. ''
  23. What is returned?
  24. -----------------
  25. Always at least one word is returned even when it is longer than the
  26. required length:
  27. >>> truncate('Lorem ipsum', 1)
  28. 'Lorem ...'
  29. If the text contains only of one word which is longer than the desired
  30. length it is returned without an ellipsis:
  31. >>> truncate('The-really-long-word', 5)
  32. 'The-really-long-word'
  33. If the text is shorter than the desired length it is returned without
  34. the ellipsis, too:
  35. >>> truncate('Lorem ipsum', 11)
  36. 'Lorem ipsum'
  37. Where gets the text truncated?
  38. ------------------------------
  39. Truncation also takes place at tabs and linebreaks:
  40. >>> truncate("I was here.\nNow I'm away", 11)
  41. 'I was here. ...'
  42. >>> truncate("I was here.\rNow I'm away", 12)
  43. 'I was here.\rNow ...'
  44. >>> truncate("I was here.\tNow I'm away", 11)
  45. 'I was here. ...'
  46. I do not want `...` as ellipsis.
  47. --------------------------------
  48. ``truncate`` takes an optional argument which defines the ellipsis string:
  49. >>> print(truncate(u'Lorem ipsum', 5, ellipsis=u':::'))
  50. Lorem :::