Python multiline string indent

Unindenting multi-line strings in Python

Sign in to your Python Morsels account to save your screencast settings.

Let’s talk about how to create a multi-line string in Python without accidentally indenting the text within that string.

Manually dedenting multi-line strings

Here we have a function that prints out a copyright statement:

def copyright(): print("""\ Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved.""" ) 

This function works, but the copyright statement that it prints out is indented:

>>> copyright() Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved. 

Each line in this copyright statement begins with eight spaces. This happens because in our code, the text within our string begins with eight spaces before each line.

We can fix this problem by manually dedenting the text within this string:

def copyright(): print("""\ Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved.""" ) 
>>> copyright() Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved. 

This also makes our code a bit tricky to read.

Читайте также:  Android java stop service

Our code is less readable than before because up here, we our code suddenly dedents in the middle of our string.

We could fix this problem in by using the dedent function in Python’s textwrap module.

Using textwrap.dedent to unindent strings

The dedent function allows us to indent our code however we’d like.

Our multi-line string can be nicely indented in our code because the dedent function will will dedent it for us:

from textwrap import dedent def copyright(): print(dedent("""\ Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved.""" )) 

At the point where we use this string, we’ll see that it doesn’t have any indentation:

>>> copyright() Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved. 

The dedent function removed the indentation for us.

Mind your newlines

Note that our string starts with a backslash ( \ ):

from textwrap import dedent def copyright(): print(dedent("""\ . )) 

That backslash removes the extra newline character ( \n ) that this string would start with if this backslash weren’t here. Without that backslash, we would need to start our text on the same line to avoid that newline character:

from textwrap import dedent def copyright(): print(dedent("""Copyright (c) 1991-2000 ACME Corp . 

Note that we’re also ending our multi-line string on the same line that our text ends:

from textwrap import dedent def copyright(): print(dedent("""\ . All Rights Reserved.""" )) 

It would be nice if we could end it on the next line instead, but that would add an extra newline at the end of our string.

I prefer to combine dedent with the string strip method to take care of these newlines.

Combining dedent with strip to make the code more readable

Here we’re using the strip method with our string:

from textwrap import dedent def copyright(): print(dedent(""" Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved. """).strip("\n")) 

The dedent function is dedenting a string that starts with a newline character and ends with a newline character (note that we end our multi-line string on the next line). After we dedent, we then use the string strip method to remove those newline characters.

Our copyright statement looks as it should:

>>> copyright() Copyright (c) 1991-2000 ACME Corp All Rights Reserved. Copyright (c) 2000-2030 Cyberdyne All Rights Reserved. 

And we have nicely indented code that doesn’t have a strange backslash. Plus we don’t need to worry about where exactly our multi-line string ends in our code: we’re ending our string on the new line and that’s okay!

dedent maintains relative indentation levels

It’s important to note that the dedent function doesn’t remove all whitespace from the beginning of each line. It’s a little bit smarter than that. The dedent function maintains relative indentation within a string.

Here we have a string that is expected to have some lines indented more than others:

from textwrap import dedent example_list = dedent(""" - Fix leap year bug - User registration breaks on leap years - Write a regression test - Record a screencast """).strip("\n") print("The list.txt file should show a bulleted list, like this:") print(example_list) 

You can see that every line has at least four spaces of indentation, but some lines have more indentation.

When we run dedent against this string, you’ll see the four spaces of indentation (that’s common to each line) is removed:

$ python3 example_list.py The list.txt file should show a bulleted list, like this: - Fix leap year bug - User registration breaks on leap years - Write a regression test - Record a screencast 

But the indentation that some lines have (that is relatively greater than other lines) is maintained.

Use textwrap.dedent to unindent strings

If you’d like to nicely format your multi-line string within your Python code without printing indented text by mistake, you can use the dedent function from Python’s textwrap module.

A Python tip every week

Need to fill-in gaps in your Python skills?

Sign up for my Python newsletter where I share one of my favorite Python tips every week.

Series: Strings

Regardless of what you’re doing in Python, you almost certainly use strings all the time. A string is usually the default tool we reach for when we don’t have a more specific way to represent our data.

To track your progress on this Python Morsels topic trail, sign in or sign up.

Источник

Python multiline string indent

In the example, we joined the strings in the list with a space separator.

However, you could also use a tab.

Copied!
my_str = """\ First line Second line Third line """ result = "\t".join(line.strip() for line in my_str.splitlines()) print(repr(result)) # 👉️ "'First line\tSecond line\tThird line'"

# Strip leading whitespace from Multiline string in Python

Use the textwrap.dedent() method to strip the leading whitespace from a multiline string in Python.

The textwrap.dedent method will remove the common leading whitespace from every line of the string.

Copied!
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 the beginning and end # first # second # third print(cleandoc(multiline_str))

strip leading whitespace from multiline string

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.

Copied!
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.

Copied!
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.

Copied!
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.

# Proper indentation for multiline strings in Python

To properly indent multiline strings:

  1. Add a backslash at the end of the first line.
  2. Close the multiline string on the last line.
  3. Use the dedent() and indent() methods if you need to dedent or indent the multiline string.
Copied!
from textwrap import dedent, indent from inspect import cleandoc multiline_str = """\ first second third""" # 👇️ with indentation # first # second # third print(multiline_str) # 👇️ without indentation # first # second # third print(dedent(multiline_str)) # 👇️ indent the multiline string a specific number of spaces # first # second # third print(indent(multiline_str, ' ')) # 👇️ using inspect.cleandoc # (removes empty lines at beginning and end, and leading whitespace) # first # second # third print(cleandoc(multiline_str))

# Add a backslash at the end of the first line

The first thing to note when using multiline strings is to add a backslash at the end of the first line.

Copied!
multiline_str = """\ first second third""" print(multiline_str)

add backslash at end of first line

If you don’t add the backslash, you’ll notice that an extra newline character gets added to the string.

# Close the multiline string on the same line

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

Copied!
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.

# Ident or dedent the multiline string

You can use the textwrap.indent() and textwrap.dedent() methods to indent or dedent the multiline string.

Copied!
from textwrap import dedent, indent multiline_str = """\ first second third""" # 👇️ without indentation # first # second # third print(dedent(multiline_str)) # 👇️ indent the multiline string a specific number of spaces # first # second # third print(indent(multiline_str, ' '))

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.

The textwrap.indent method takes a multiline string and a prefix and adds the prefix to the beginning of each line of the string.

By default, the method adds the prefix to the beginning of each line that doesn’t consist only of whitespace.

# Remove the empty lines at the beginning and end of the multiline string

You can also use the inspect.cleandoc method if you want to remove the empty lines at the beginning and end of the multiline string and the leading whitespace.

Copied!
from inspect import cleandoc multiline_str = """ first second third """ # # first # second # third # print(multiline_str) # first # second # third print(cleandoc(multiline_str))

I intentionally didn’t add a backslash at the end of the first line and didn’t close the multiline string on the same line.

Notice that the inspect.cleandoc method removed the empty lines at the beginning and end of the string and removed 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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Оцените статью