Content · Programming · Python

Python textwrap.indent() Function: Usage and Examples

Add a prefix to selected lines of a multiline string.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Add a prefix to selected lines of a multiline string.

How It Works


textwrap.indent(text, prefix, predicate=None) inserts a prefix at the start of lines chosen by a predicate. By default blank lines are not prefixed.

Step-by-Step Example


import textwrap
indented_text = textwrap.indent('alpha\nbeta\n', '> ')
print(indented_text.splitlines())

Understanding the Example


  • The expression "textwrap.indent('alpha\\nbeta\\n', '> ')" supplies the value stored as 'indented_text'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

['> alpha', '> beta']

Where This Fits in a Real Program


Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.

Practice: Try It Yourself


Provide a predicate to control which lines are prefixed.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Assuming blank lines are prefixed automatically or that indent changes the original string.
  • Quote a multiline comment using a four-space prefix.

Key Takeaways


  • Add a prefix to selected lines of a multiline string.
  • textwrap.indent(text, prefix, predicate=None) inserts a prefix at the start of lines chosen by a predicate.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.