hbutils.string.trunc

String truncation utilities for producing readable short text previews.

This module provides functionality for truncating long strings into shorter forms with customizable output width, optional tail display, and optional length indicators. The core public utility is truncate(), which is a thin wrapper around textwrap.shorten() with additional placeholder configuration.

The module contains the following main components:

  • truncate() - Truncate text with optional tail and length indicators.

Note

The underlying implementation relies on textwrap.shorten(), which collapses consecutive whitespace and attempts to break on word boundaries.

Warning

If the width is smaller than the placeholder length produced by show_length and tail_length options, textwrap.shorten() will raise ValueError.

Example:

>>> from hbutils.string.trunc import truncate
>>> truncate('abc ' * 30, width=30)
'abc abc abc abc abc abc ... '
>>> truncate('abc ' * 30, width=40, tail_length=10)
'abc abc abc abc abc abc ... c abc abc '
>>> truncate('abc ' * 30, width=40, tail_length=10, show_length=True)
'abc abc abc ..(120 chars).. c abc abc '

__all__

hbutils.string.trunc.__all__ = ['truncate']

Built-in mutable sequence.

If no argument is given, the constructor creates a new empty list. The argument must be an iterable if specified.

truncate

hbutils.string.trunc.truncate(text: str, width: int = 70, tail_length: int = 0, show_length: bool = False) str[source]

Truncate a string into a short, readable form.

This function shortens the given text to fit within width characters. The truncation placeholder can include the total character count of the original text and an optional tail segment, controlled via show_length and tail_length. Internally, textwrap.shorten() is used, meaning whitespace is normalized and truncation occurs on word boundaries where possible.

Parameters:
  • text (str) – Original text to be truncated.

  • width (int, optional) – Maximum width of the resulting string, defaults to 70.

  • tail_length (int, optional) – Number of characters from the end of text to append to the placeholder, defaults to 0 (no tail).

  • show_length (bool, optional) – Whether to include the original text length in the placeholder, defaults to False.

Returns:

Truncated string fitting within the given width.

Return type:

str

Raises:

ValueError – If width is smaller than the computed placeholder length, as enforced by textwrap.shorten().

Note

The input is converted to str before processing, so non-string inputs will be stringified.

Example:

>>> from hbutils.string import truncate
>>> truncate('abc ' * 30, width=30)
'abc abc abc abc abc abc ... '
>>> truncate('abc ' * 30, width=40, tail_length=10)
'abc abc abc abc abc abc ... c abc abc '
>>> truncate('abc ' * 30, width=40, tail_length=10, show_length=True)
'abc abc abc ..(120 chars).. c abc abc '