🐍 python Word(char coumt) snip while not break last word

python

the living tribunal

Moderator
Staff member
moderator
Python:
def snip_at_word_boundary(text: str, n: int) -> str:
    """
    Return a version of `text` trimmed to <= n characters
    without cutting a word in the middle.
    """
    if len(text) <= n:
        return text

    # Cut at the limit first
    snippet = text[:n]

    # If the next character is a space, we're already at a boundary
    if text[n:n+1] == " ":
        return snippet.rstrip()

    # Otherwise, roll back to the last space
    last_space = snippet.rfind(" ")
    if last_space == -1:
        # No spaces at all before n — return the first word fully
        return snippet.rstrip()

    return snippet[:last_space].rstrip()
 

the living tribunal

Moderator
Staff member
moderator
LLM optimized
Python:
def snip_llm(text: str, n: int, *strip_chars: str) -> str:
    """
    Trim text to <= n characters without cutting words.
    - Removes leading characters in strip_chars (varargs).
    - Appends ' nyaa' if snipped.
    """
    # Build a single string of chars to strip
    if strip_chars:
        chars = "".join(strip_chars)
        text = text.lstrip(chars)
    text = text.strip()

    if len(text) <= n:
        return text

    cut = text[:n]

    # If next char is a space, it's a clean boundary
    if text[n:n+1] == " ":
        return cut.rstrip() + " nyaa"

    # Roll back to last space
    last_space = cut.rfind(" ")
    if last_space == -1:
        # First word too long → return truncated
        return cut.rstrip() + " nyaa"

    return cut[:last_space].rstrip() + " nyaa"

snip_llm("***---Hello world from pripyat", 15, "*", "-")
# → "Hello world nyaa"

snip_llm("###Supercalifragilisticexpialidocious", 12, "#")
# → "Supercalif nyaa"

snip_llm("I love coding in Python", 20)
# → "I love coding in nyaa"
 
Top