Remove shared indentation from multiline source text.
How It Works
textwrap.dedent() removes consistent leading whitespace across nonblank lines, making triple-quoted text easier to embed in functions. It does not remove an arbitrary fixed amount from every line.
Step-by-Step Example
import textwrap
text = " first\n second\n"
print(textwrap.dedent(text).strip().splitlines())
Understanding the Example
- The expression '" first\\n second\\n"' supplies the value stored as '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:
['first', 'second']
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
Use strip() after dedent() when boundary blank lines must be removed.
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
- Expecting dedent() to remove the first newline of a triple-quoted string automatically.
- Prepare a multiline SQL sample for readable terminal output.
Key Takeaways
- Remove shared indentation from multiline source text.
- textwrap.dedent() removes consistent leading whitespace across nonblank lines, making triple-quoted text easier to embed in functions.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.