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 textwraptxt = '''hello educativehello edpresso'''indent_str = "!!!"print("Example 1:")print(textwrap.indent(txt, indent_str))pred = lambda x: x.startswith("hello")txt = '''hello educativeedpresso hello'''print("Example 2:")print(textwrap.indent(txt, indent_str, predicate=pred))
Explanation
- Line 1: We import the
textwrapmodule. - Lines 3–4: We define the text in
txtwith 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
predthat returnsTrueif the given input starts with the stringhello. Otherwise, the predicate returnsFalse. - Lines 16–20: We define a new value for
txt. - Line 11: We invoke the
indent()method withtxt,indent_strandpredas parameters. We can observe in the output that only the text lines starting withhelloare prefixed withindent_str.