What is textwrap.dedent() in Python?

The textwrap module

The textwrap module in Python is an in-built module. This module provides functions for wrapping, filling, and formatting plain text. For example, we can adjust the line breaks in an input paragraph using the textwrap module.

The dedent method

The dedent method removes any common leading whitespace from each line of the provided text. In the input, lines containing only whitespace are disregarded. These are normalized to a single newline character in the output.

textwrap.dedent(text)

Parameter

text: This is the text to be dedented.

Code

import textwrap
txt = '''
'''
print("dedent of string containing only whitespace is %s" % (textwrap.dedent(txt).encode("unicode_escape"), ))
txt = '''
hello educative!!
'''
print(textwrap.dedent(txt).encode("unicode_escape"))

Code explanation

  • Line 1: The textwrap module is imported.
  • Lines 4–14: The dedent() method is invoked with different outputs. The output of the method is escaped so that the newline character inserted is printed.

Free Resources