libb.truncate

truncate(s, width, suffix='...')[source]

Truncate a string to max width characters.

Adds suffix if the string was truncated. Tries to break on whitespace.

Parameters:
  • s (str) – String to truncate.

  • width (int) – Maximum width including suffix.

  • suffix (str) – Suffix to append when truncated.

Returns:

Truncated string.

Return type:

str

Raises:

AssertionError – If width is not longer than suffix.

Example:

>>> truncate('fubarbaz', 6)
'fub...'
>>> truncate('fubarbaz', 3)
Traceback (most recent call last):
    ...
AssertionError: Desired width must be longer than suffix
>>> truncate('fubarbaz', 3, suffix='..')
'f..'