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, 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.

Example

import textwrap
txt = '''
The `textwrap` module in Python is an in-built module.
'''
width = 50
short_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 textwrap module.
  • Lines 3–5: We define the text in txt.
  • Line 7: We define the width to be shortened to.
  • Line 9: We invoke the shorten() method with txt and width.
  • Lines 11–13: We print the original and shortened text.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources