Drill

ProblemsPython › text

Cut a description to length

mediumtextPython

A listing card has room for a fixed number of characters, and a description cut mid-word looks broken.

truncate_words(text: string, limit: int) → string

Solve it in the editor →

Where you start

def truncate_words(text: str, limit: int) -> str:
    

Worked examples

CallResult
truncate_words("The quick brown fox", 10)"The quick..."
truncate_words("Supercalifragilistic", 5)"Super..."
truncate_words("Short", 10)"Short"
truncate_words("a b c d e f", 5)"a b c..."

Hint

Look at the character sitting at `limit`: if it is a space, the slice is already clean and needs no trimming back.

Reference solution in Python
def truncate_words(text: str, limit: int) -> str:
    if limit <= 0:
        return ''
    if len(text) <= limit:
        return text
    cut = text[:limit]
    if text[limit] != ' ':
        sp = cut.rfind(' ')
        if sp > 0:
            cut = cut[:sp]
    return cut.rstrip() + '...'

The same problem in another language

More text problems in Python