24-truncate.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. """
  2. Write a function called truncate that will shorten a string
  3. to a specified length, and add "..." to the end. Given a
  4. string and a number, truncate the string to a shorter string
  5. containing at most n characters. For example,
  6. truncate("long string", 5) should return a 5 character truncated
  7. version of "long string". If the string gets truncated, the
  8. truncated return string should have a "..." at the end. Because
  9. of this, the smallest number passed in as a second argument should
  10. be 3.
  11. """
  12. def truncate(text: str, trunc: int):
  13. if trunc < 3:
  14. return "Truncation must be at least 3 characters."
  15. return text[0:trunc-3] + "..." if trunc <= len(text) else text
  16. print(truncate("Hello World", 6))
  17. '''
  18. truncate("Super cool", 2) # "Truncation must be at least 3 characters."
  19. truncate("Super cool", 1) # "Truncation must be at least 3 characters."
  20. truncate("Super cool", 0) # "Truncation must be at least 3 characters."
  21. truncate("Hello World", 6) # "Hel..."
  22. truncate("Problem solving is the best!", 10) # "Problem..."
  23. truncate("Another test", 12) # "Another t..."
  24. truncate("Woah", 4) # "W..."
  25. truncate("Woah", 4) # "..."
  26. truncate("Yo",100) # "Yo"
  27. truncate("Holy guacamole!", 152) # "Holy guacamole!"
  28. '''