Skip to content

Truncated Strings

trunc_str

trunc_str

trunc_str(text, max_chars, placeholder='...')

A function that truncates a string to a maximum number of characters, appending a placeholder if truncation occurs.

Example

Basic usage:

from stringz import trunc_str trunc_str("hello world", max_chars=10) 'hello w...'

No truncation needed:

trunc_str("short", max_chars=10) 'short'

Custom placeholder:

trunc_str("hello world", max_chars=10, placeholder=">>") 'hello wo>>'

Empty placeholder:

trunc_str("hello world", max_chars=5, placeholder="") 'hello'

Parameters:

Name Type Description Default
text str

The string to be truncated.

required
max_chars int

The maximum number of characters allowed in the output string.

required
placeholder str

The string to append if truncation occurs. Default is '...'.

'...'

Returns:

Type Description
str

The truncated string, if necessary, with the placeholder appended.

Raises:

Type Description
TypeError

If text is not a string.

ValueError

If max_chars is not a positive integer or if placeholder length is greater than or equal to max_chars.

TypeError

If placeholder is not a string.

ValueError

If placeholder length is greater than or equal to max_chars.

Source code in src/stringz/_truncated_string.py
def trunc_str(
    text: str,
    max_chars: int,
    placeholder: str = "...",
) -> str:
    """A function that truncates a string to a maximum number of characters,
    appending a placeholder if truncation occurs.

    Example:
        Basic usage:

        >>> from stringz import trunc_str
        >>> trunc_str("hello world", max_chars=10)
        'hello w...'

        No truncation needed:

        >>> trunc_str("short", max_chars=10)
        'short'

        Custom placeholder:

        >>> trunc_str("hello world", max_chars=10, placeholder=">>")
        'hello wo>>'

        Empty placeholder:

        >>> trunc_str("hello world", max_chars=5, placeholder="")
        'hello'

    Args:
        text: The string to be truncated.
        max_chars: The maximum number of characters allowed in the output string.
        placeholder: The string to append if truncation occurs. Default is '...'.

    Returns:
        The truncated string, if necessary, with the placeholder appended.

    Raises:
        TypeError: If text is not a string.
        ValueError: If max_chars is not a positive integer or if placeholder length is greater than or
            equal to max_chars.
        TypeError: If placeholder is not a string.
        ValueError: If placeholder length is greater than or equal to max_chars.
    """

    # ====> VALIDATION
    if not isinstance(text, str):
        _err: str = f"text must be a string, not {type(text).__name__}"
        raise TypeError(_err)
    if not isinstance(max_chars, int) or max_chars <= 0:
        _err: str = f"max_chars must be a positive integer, got {max_chars}"
        raise ValueError(_err)
    if not isinstance(placeholder, str):
        _err: str = f"placeholder must be a string, not {type(placeholder).__name__}"
        raise TypeError(_err)
    if len(placeholder) >= max_chars:
        _err: str = f"placeholder length ({len(placeholder)}) must be smaller than max_chars ({max_chars})"
        raise ValueError(_err)

    # ====> TRUNCATE
    if len(text) <= max_chars:
        return text
    return text[: max_chars - len(placeholder)] + placeholder

TStr

TStr

Bases: str

A string subclass that automatically truncates its content to a maximum length when created or modified through string operations. The TStr class uses the trunc_str function for truncation under the hood.

Example

Basic creation:

from stringz import TStr s = TStr("hello world", max_chars=10) print(s) hello w... len(s) 10

String operations maintain TStr type and truncation:

s1 = TStr("hello", max_chars=10) s2 = s1 + " world" type(s2) <class 'stringz._truncated_string.TStr'> print(s2) hello w...

Attributes

max_chars instance-attribute

max_chars

placeholder instance-attribute

placeholder