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
1 2 3 |
str1 = "This is a long sentence that spans\ multiple lines." print("str1: ", str1) |
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,
1 2 3 |
str2 = "This is a long sentence that spans\a multiple lines." print("str2: ", str2) |
Output:
SyntaxError: EOL while scanning string literal
1 2 3 4 |
# There is a white space after the backslash str3 = "This is a long sentence that spans\ multiple lines." print("str1: ", str3) |
Output:
SyntaxError: EOL while scanning string literal
Method 2: Using Parentheses
1 2 3 |
str2 = ("This is a long sentence that spans" "multiple lines.") print("str2: ", str2) |
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,
1 2 3 4 5 6 7 8 9 10 11 |
def sum1(a, b): """ Input: a - numeric and b - numeric The function returns the sum of the two numbers. """ return a + b result = sum1(4, 5) print(result) # Fetch the documentation docstring = sum1.__doc__ print(docstring) |
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.
1 2 3 |
str4 = """This is a long sentence that spans multiple lines.""" print(str4) |
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.