Python 3.4+textwrapfunction
textwrap.shorten
wrapping
Collapse and truncate text to fit `width`, replacing the tail with a placeholder.
Syntax
textwrap.shorten(text, width, placeholder=' [...]')
It normalizes whitespace first — every run of spaces and newlines collapses to a single space — so it is not the tool for "keep the first N characters"; a plain slice is. Truncation happens at word boundaries and the placeholder counts toward width: if not even the first word fits you get the placeholder alone, and a placeholder longer than width raises ValueError.
Examples
import textwrap
print(textwrap.shorten('Hello world foo', 12, placeholder='...')) # → Hello...
print(textwrap.shorten('Python is a great language', 20)) # → Python is a [...]
print(textwrap.shorten(' a b ', 10)) # → a b
print(textwrap.shorten('Hello world!', 10)) # → [...]
print('Hello world foo'[:8]) # → Hello wo
See also
Open in the full glossarydocs.python.orgReport an inaccuracy