Content · Programming · Python

Python textwrap.shorten() Function: Usage and Examples

Shorten text without abruptly cutting through a word.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Shorten text without abruptly cutting through a word.

How It Works


textwrap.shorten(text, width, placeholder=" [...]") collapses whitespace and truncates at word boundaries when needed. The placeholder length must fit inside width.

Step-by-Step Example


import textwrap
summary = textwrap.shorten('A longer message about package updates', width=24, placeholder='...')
print(len(summary) <= 24)
print(summary.endswith('...'))

Understanding the Example


  • The expression "textwrap.shorten('A longer message about package updates', width=24, placeholder='...')" supplies the value stored as 'summary'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

True
True

Where This Fits in a Real Program


Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.

Practice: Try It Yourself


Use string slicing for exact character limits, and shorten for word-aware text.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Expecting shorten() to preserve original whitespace or accepting a placeholder longer than width.
  • Generate a compact preview label from a long sentence.

Key Takeaways


  • Shorten text without abruptly cutting through a word.
  • textwrap.shorten(text, width, placeholder=" [...]") collapses whitespace and truncates at word boundaries when needed.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.