boltons icon indicating copy to clipboard operation
boltons copied to clipboard

Proposal: shorten long string by truncate chars (not by words)

Open guyskk opened this issue 3 years ago • 0 comments

The standard lib textwrap.shorten truncates words, not single characters. And there doesn't seem a way to configure shorten() or a TextWrapper instance to clip single characters and not words.

See also comments in: https://stackoverflow.com/a/39017530/6626292

Proposal implementation:

def shorten(text, width, placeholder="..."):
    """
    >>> shorten('123456789', width=8)
    '12345...'
    >>> shorten('123456789', width=9)
    '123456789'
    >>> shorten(None, width=8) is None
    True
    """
    if not text:
        return text
    if len(text) <= width:
        return text
    return text[: max(0, width - len(placeholder))] + placeholder

The function name shorten may change to diff with textwrap.shorten, maybe shorten_chars or better ideas?

If appropriate, I'm glad to submit a PR.

guyskk avatar Jan 30 '22 07:01 guyskk