Multiline Strings in Python

Triple Quotes

To handle multiline strings in Python you use triple quotes, either single or double.

This first example uses double quotes.

long_text = """This is a multiline,

a long string with lots of text,

I'm wrapping it in triple quotes to make it work."""

print(long_text)
#output:
#This is a multiline,
#
#a long string with lots of text,
#
#I'm wrapping it in triple quotes to make it work.

Now the same as before, but with single quotes.

long_text = '''This is a multiline,

a long string with lots of text,

I'm wrapping it in triple quotes to make it work.'''

print(long_text)
#output:
#This is a multiline,
#
#a long string with lots of text,
#
#I'm wrapping it in triple quotes to make it work.

Notice both outputs are the same.

Parentheses

Let’s see an example with parentheses.

long_text = ("This is a multiline, "
"a long string with lots of text "
"I'm wrapping it in brackets to make it work.")
print(long_text)
#This is a multiline, a long string with lots of text I'm wrapping it in triple quotes to make it work.

As you can see, the result is not the same, to achieve new lines I have to add \n, like this:

long_text = ("This is a multiline, \n\n"
"a long string with lots of text \n\n"
"I'm wrapping it in brackets to make it work.")
print(long_text)
#This is a multiline, 
#
#a long string with lots of text 
#
#I'm wrapping it in triple quotes to make it work.

Backlashes

Finally, backlashes are also a possibility.

Notice there is no space after the \ character, it would throw an error otherwise.

long_text = "This is a multiline, \n\n" \
"a long string with lots of text \n\n" \
"I'm using backlashes to make it work."
print(long_text)
#This is a multiline, 
#
#a long string with lots of text 
#
#I'm wrapping it in triple quotes to make it work.