Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
guyskk opened this issue Jan 30, 2022 · 0 comments
Open

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

guyskk opened this issue Jan 30, 2022 · 0 comments

Comments

@guyskk
Copy link

guyskk commented Jan 30, 2022

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant