What is the textwrap.shorten() method in Python?
Overview
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.
The shorten() method
The 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.
Syntax
textwrap.shorten(text, width, *, fix_sentence_endings=False, break_long_words=True, break_on_hyphens=True, placeholder=' [...]')
Parameters
text: This is the text to be shortened.width: The width the given to fit into.fix_sentence_endings: If this value is true, theTextWrappermodule 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 isTrue.break_on_hyphens: A boolean indicating whether to break on hyphens or not. The default value isTrue.placeholder: The placeholder to use.
Example
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)
Explanation
- Line 1: We import the
textwrapmodule. - Lines 3–5: We define the text in
txt. - Line 7: We define the
widthto be shortened to. - Line 9: We invoke the
shorten()method withtxtandwidth. - Lines 11–13: We print the original and shortened text.