Strip leading whitespace from Multiline string in Python

avatar

Borislav Hadzhiev

Last updated: Aug 13, 2022

banner

Photo from Unsplash

Strip leading whitespace from Multiline string in Python #

Use the textwrap.dedent() method to strip the leading whitespace from a multiline string in Python, e.g. print(dedent(multiline_str)). The textwrap.dedent method will remove the common leading whitespace from every line of the string.

main.py
from textwrap import dedent from inspect import cleandoc multiline_str = """\ first second third""" # 👇️ remove indentation # first # second # third print(dedent(multiline_str)) # 👇️ removes indentation and empty lines at beginning and end # first # second # third print(cleandoc(multiline_str))

The first example uses the textwrap.dedent method to remove the leading whitespace from the multiline string.

The textwrap.dedent method takes a multiline string and removes the common leading whitespace from every line of the string.

The method is used to display multiline strings that are indented in the source code without any indentation.

Note that we used a backslash at the end of the first line of the multiline string.

main.py
multiline_str = """\ first second third"""
If you don't add the backslash, you'll notice that an extra newline character gets added to the string.

Make sure to close the multiline string on the same line.

main.py
multiline_str = """\ first second third""" # 👈️ close on same line print(multiline_str)

If you don't close the multiline string on the same line, an extra newline character gets added at the end of the string.

If your multiline string has empty lines at the beginning or end, use the inspect.cleandoc() method to remove them and remove the leading whitespace.

main.py
from inspect import cleandoc multiline_str = """ first second third """ # 👇️ removes indentation and empty lines at beginning and end # first # second # third print(cleandoc(multiline_str))

We didn't use a backslash at the end of the first line of the string and didn't close the multiline string on the same line, so the string has an empty line at the beginning and at the end.

The inspect.cleandoc() method takes care of removing the empty lines at the beginning and end and the leading whitespace.

If you don't want to remove the empty lines at the beginning and end of the multiline string, use the textwrap.dedent() method.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.