textwrap
moduleThe 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
methodThe 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)
.
textwrap.indent(text, prefix, predicate=None)
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.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))
textwrap
module.txt
with newline characters.indent_str
.indent()
method.pred
that returns True
if the given input starts with the string hello
. Otherwise, the predicate returns False
.txt
.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
.