How to Continue a String to the Next Line in Python?

Estimated read time 2 min read

In Python, you can continue a string to the next line using parentheses (), braces {}, or brackets []. Here’s an example:

message = ("This is a long string "
           "that continues on the next line "
           "without any explicit line continuation.")

print(message)

In this example, the string is enclosed within parentheses (), but you can also use braces {} or brackets []. The string is spread across multiple lines without the need for explicit line continuation.

When Python encounters an opening parenthesis, brace, or bracket without a closing counterpart, it automatically continues the line to the next line. This behavior can be used to continue a string without the need for explicit line continuation characters.

The output of this example will be:

This is a long string that continues on the next line without any explicit line continuation.

Note that Python automatically removes leading and trailing whitespace when joining the lines in this manner. If you want to preserve the whitespace, you can use triple quotes ''' or """ to define a multiline string:

message = '''This is a long string
that continues on the next line
with preserved whitespace.'''

print(message)

The output will be:

This is a long string
that continues on the next line
with preserved whitespace.

Using triple quotes allows you to create multiline strings with explicit line breaks and preserve the whitespace as it appears in the code.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply