Dedenting

The Python standard library has two very useful functions to support removing indentation, but they’re not in obvious places!

inspect.cleandoc(doc):

Clean up indentation from docstrings that are indented to line up with blocks of code. Any whitespace that can be uniformly removed from the second line onwards is removed. Also, all tabs are expanded to spaces.

What it doesn’t tell you is that it also removes trailing newlines!

textwrap.dedent(text):

Remove any common leading whitespace from every line in text.

This can be used to make triple-quoted strings line up with the left edge of the display, while still presenting them in the source code in indented form.

See the links for the full docs, including handling of whitespace.

This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a comment