Back to Freecodecamp

Challenge 178: Truncate the Text

curriculum/challenges/english/blocks/daily-coding-challenges-python/69738771fb5a7b8b24cca2a4.md

latest1.4 KB
Original Source

--description--

Given a string, return it as-is if it's 20 characters or shorter. If it's longer than 20 characters, truncate it to the first 17 characters and append "..." to the end of it (so it's 20 characters total) and return the result.

--hints--

truncate_text("Hello, world!") should return "Hello, world!".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(truncate_text("Hello, world!"), "Hello, world!")`)
}})

truncate_text("This string should get truncated.") should return "This string shoul...".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(truncate_text("This string should get truncated."), "This string shoul...")`)
}})

truncate_text("Exactly twenty chars") should return "Exactly twenty chars".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(truncate_text("Exactly twenty chars"), "Exactly twenty chars")`)
}})

truncate_text(".....................") should return "....................".

js
({test: () => { runPython(`
from unittest import TestCase
TestCase().assertEqual(truncate_text("....................."), "....................")`)
}})

--seed--

--seed-contents--

py
def truncate_text(text):

    return text

--solutions--

py
def truncate_text(text):
    if len(text) <= 20:
        return text
    return text[:17] + "..."