Proper Indentation for Python Multiline Strings

Python Mutliline Strings

In this article we are going to look at how to properly indent your code for Python multiline strings, so let’s start by clarifying what a multiline string is and why indentation is important. Readability for other users is one of the key requirements of writing effective Python code, so having a very long string on a single line contradicts this basic requirement. The three main ways to split a string in Python are triple quotes ('''), brackets (()) and the backslash (\), all of which we will look at in more detail.

Proper indentation, on the other hand, is less about aesthetics but is a requirement with Python as it tells the interpreter that a series of statements belong to a particular block of code. Incorrect indentation could therefore lead to errors or code not running as required.

Let’s use an example of a long string and see the different methods we have for both creating a multiline string and properly indenting it:  

# No!
string = "no matter how much experience you have coding in Python, making your code readable is vital so very, very long lines need to be split"

The ‘Triple Quotes’ Method

One of the most common, and simplest, ways of splitting our string is the triple quotes method. We can use either three single (''') or double (""") quotes, and anything within the quotes becomes part of the multiline string. For example, we can use the enter button to break our string as follows:

# Yes!
string='''no matter how much experience you have coding in Python,
making your code readable is vital so
very, very long lines need to be split'''

Whilst this is a definite improvement, the readability can still be improved by indentation. The simplest way of doing this is to line subsequent lines with the initial '''.

string='''no matter how much experience you have coding in Python,
       making your code readable is vital so
       very, very long lines need to be split'''

So that was easy. We have created a multiline string and properly indented it… job done!

Unfortunately, it’s not so easy as literally anything included within the quotes becomes part of the string – whitespaces, newlines, and indentations included. So, if we need to run or postprocess the code, by printing for example, will the output be what we wanted?

no matter how much experience you have coding in Python,
       making your code readable is vital so
       very, very long lines need to be split

Unfortunately not, whilst our initial line has been aligned to the left, subsequent lines have maintained the formatting we included to make the code readable. So, we now need to get rid of any whitespaces or indentation we do not need and there are two main ways of doing this.

Indentation with textwrap.dedent

The textwrap module can be used for formatting and wrapping of plain text. In the case of multiline strings, we can use it to remove common leading whitespace from every line.

Let’s look at our example again:

import textwrap
string=textwrap.dedent('''\
        no matter how much experience you have coding in Python,
        making your code readable is vital so
        very, very long lines need to be split''')
print(string)

The output:

no matter how much experience you have coding in Python,
making your code readable is vital so
very, very long lines need to be split

The first step was to import the textwrap module. We then enclosed our actual string within the textwrap.dedent function, and in doing so our lines of string have been automatically indented. In addition, we started our string with the backslash ' \' to ensure our string starts on the new line.

The key thing to note with this module is the whitespace must be ‘common’ i.e., consistent to work effectively. So, what happens if it is not, and we add additional whitespace and indents?

import textwrap
string=('''\
      	no matter how much experience you have coding in Python,
        	 making your code readable is vital so
           	     very, very long lines need to be split''')
print(textwrap.dedent(string))

Output:

no matter how much experience you have coding in Python,
 making your code readable is vital so
   very, very long lines need to be split

Instead of wrapping our string in the textwrap.dedent function, this time we called it as part of our print statement. Whilst this did not affect the outcome, the different levels of indentation from the first line to the third meaning that the text has not been aligned as the whitespace is not consistent.

Indentation With inspect.cleandoc

An alternative to the textwrap module is the inspect module, and the cleandoc function. The purpose of this function is to uniformly remove any whitespace from the second line onwards.

If we look again at our original string:

string = '''
        no matter how much experience you have coding in Python,
        making your code readable is vital so
        very, very long lines need to be split'''
print(string)
		no matter how much experience you have coding in Python,
		making your code readable is vital so
		very, very long lines need to be split

Now let’s see what happens when we import the inspect module and run inspect.cleandoc:

import inspect
string = inspect.cleandoc('''
        no matter how much experience you have coding in Python,
        making your code readable is vital so
        very, very long lines need to be split''')
print(string)

Output:

no matter how much experience you have coding in Python,
making your code readable is vital so
very, very long lines need to be split

As we saw with the textwrap module because we have enclosed our multiline string in the function it is automatically indented. Our output has also been aligned to the left and whitespace has been removed, but in this example, we have consistent whitespace. Let’s see what happens if we make this inconsistent:

string=('''\
      	no matter how much experience you have coding in Python,
        	 making your code readable is vital so
           	     very, very long lines need to be split''')
print(inspect.cleandoc(string))
no matter how much experience you have coding in Python,
making your code readable is vital so
    very, very long lines need to be split

Unlike the textwrap module with inspect the multiline string has been aligned to the left and the third line indentation has kept the alignment with line two.

The ‘Brackets’ Method

An alternative to using triple quotes (''') to create a multiline string is to enclose the entire string in brackets (()) and split our string using the enter button. This will automatically indent each line correctly as everything within the brackets is be considered one block of code. Each line of the string, however, will need to be enclosed in ("") or ('') as follows:

string = ("no matter how much experience you have coding in Python,"
          "making your code readable is vital so"
          "very, very long lines need to be split")

This certainly solves the issue around indentation as this is done automatically. Now let’s see what happens when we want to use our code, using the print() function again:

print(string)
no matter how much experience you have coding in Python,making your code readable is vital sovery, very long lines need to be split

So, whilst the brackets method helps with the indentation, there is still an issue with postprocessing meaning we must format the string accordingly – for printing we need to format it according to how we would like it printed. In this example, we will include a newline break (\n) after every sentence, but it could equally be including whitespace, further indentation, or other format requirements:

string = ("no matter how much experience you have coding in Python,\n"
          "making your code readable is vital so\n"
          "very, very long lines need to be split")
print(string) 
no matter how much experience you have coding in Python,
making your code readable is vital so
very, very long lines need to be split

The ‘Backslash’ Method

Another alternative for creating multiline strings in Python is by using a backslash (\) to split our string and enclose each line of the string in quote marks. Unlike the bracket’s method, the multiline string is not automatically indented:

string = "no matter how much experience you have coding in Python,"\
"making your code readable is vital so"\
"very, very long lines need to be split"
print(string)
no matter how much experience you have coding in Python,making your code readable is vital sovery, very long lines need to be split

With this method not only do we have to manually indent the multiline string, so it follows the Python readability guidelines, we also have to format according to the way we want to post-process. Therefore, if we want each line of our string to be a newline, we must manually insert the newline break (or whitespace) in addition to manually indenting for readability:

string = "no matter how much experience you have coding in Python,\n"\
        "making your code readable is vital so\n"\
        "very, very long lines need to be split"
print(string)
no matter how much experience you have coding in Python,
making your code readable is vital so
very, very long lines need to be split

Summary

One of the best things about working in Python is that it offers multiple solutions to most issues, very rarely is it a case of only one answer. The toughest part is finding the most appropriate solution that best suits you and your requirements.

Of the methods of creating and indenting a multiline string we have looked at in this article, there is the only one that, in my opinion, offers the most logical solution:

💡 Enclosing our multiline string in triple quotes within the inspect.cleandoc function not only ensures our initial indentation is correct for readability but also gives us consistency when we run our code. This for me covers the fundamental requirements of any Python script.