Line Continuation with Strings in Python

Breaking a long string across multiple lines in Python improves the readability of the code. There are three ways of defining line continuation in Python strings:

  • Method 1: Using backslash (\) character,
  • Method 2: Using parentheses and,
  • Method 3: Using triple quotes

Method 1: Using Backslash Character

Output:

str1:  This is a long sentence that spans multiple lines.

In the example above, using a backslash indicates that the string continues in the next line.

Be careful: Do not hard any other character (not even whitespace) after the backslash. If you do so, you will end up with a SyntaxError. For example,

Output:

SyntaxError: EOL while scanning string literal

Output:

SyntaxError: EOL while scanning string literal

Method 2: Using Parentheses

The parentheses in this method groups string segments together, and the Python interpreter will view it as a single string.

Method 3: Using Triple Quotes

Ideally, triple quotes are used for docstring – a string used to document a Python function or class. For example,

Output:

9
Input: a - numeric and b - numeric
The function returns the sum of the two numbers.

Despite its primary use to define docstrings, we can repurpose triple quotes to define multi-line strings, as shown below.

Output:

This is a long sentence that spans
 multiple lines.

Note: You can also use three single quotes for opening and closing the multi-line string.

Conclusion

This guide discusses three methods for breaking a long string across multiple lines in Python. The first method (using a backslash) is the most common, but the other two also serve the purpose.

When using a backslash in Method 1, ensure you do not add any other character (not even whitespace) after the backslash; otherwise SyntaxError will be raised.