The textwrap
module in Python is an in-built module. This module provides functions to wrap, fill, and format plain text. For example, we can adjust the line breaks in an input paragraph using the textwrap
module.
shorten()
methodThe shorten()
method collapses and truncates the given text to fit in the given width. The whitespace in the text is first compacted (all whitespace is replaced by single spaces). The result is returned if it fits inside the width. Otherwise, enough words are removed from the end to fit the remaining words and the placeholder within the available space.
textwrap.shorten(text, width, *, fix_sentence_endings=False, break_long_words=True, break_on_hyphens=True, placeholder=' [...]')
text
: This is the text to be shortened.width
: The width the given to fit into.fix_sentence_endings
: If this value is true, the TextWrapper
module will try to identify sentence ends and ensure that sentences are always separated by exactly two spaces.break_long_words
: A boolean indicating whether to break longer words or not. The default value is True
.break_on_hyphens
: A boolean indicating whether to break on hyphens or not. The default value is True
.placeholder
: The placeholder to use.import textwraptxt = '''The `textwrap` module in Python is an in-built module.'''width = 50short_txt = textwrap.shorten(txt, width=width)print("original text is - ", txt)print("-" * 5)print("Shortened text is - \n", short_txt)
textwrap
module.txt
.width
to be shortened to.shorten()
method with txt
and width
.