What is textwrap.indent() in Python?

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.

indent method

The indent method adds the specified prefix to the beginning of the chosen text lines. Controlling which lines are indented can be done with the predicate parameter.

The lines in the text are separated by calling text.splitlines(True).

Syntax

textwrap.indent(text, prefix, predicate=None)

Parameters

  • text: This is the text that is to be indented.
  • prefix: This is the prefix to be added to the beginning of the text lines.
  • predicate: This can be used to control which lines in the text are indented.

Code example

import textwrap
txt = '''
hello educative
hello edpresso
'''
indent_str = "!!!"
print("Example 1:")
print(textwrap.indent(txt, indent_str))
pred = lambda x: x.startswith("hello")
txt = '''
hello educative
edpresso hello
'''
print("Example 2:")
print(textwrap.indent(txt, indent_str, predicate=pred))

Explanation

  • Line 1: We import the textwrap module.
  • Lines 3–4: We define the text in txt with newline characters.
  • Line 9: We define the prefix to be added in indent_str.
  • Line 11: We print the output of the indent() method.
  • Line 14: We define a predicate called pred that returns True if the given input starts with the string hello. Otherwise, the predicate returns False.
  • Lines 16–20: We define a new value for txt.
  • Line 11: We invoke the indent() method with txt, indent_str and pred as parameters. We can observe in the output that only the text lines starting with hello are prefixed with indent_str.

Free Resources