12. Multiline strings

A triple-quoted string starts and ends with three quotes and can span several physical lines:

The newline between the lines is inside the string, so text contains "Line one\nLine two". Everything between the opening and closing quotes is content, including the line breaks.

You can use """...""" or '''...'''; choose the one that does not appear in your text. Triple quotes also let you write both " and ' without escaping:

A backslash at the end of a line inside a normal string joins the next physical line into the same logical line. The newline and the backslash disappear:

Coming from JavaScript? Triple quotes are like backticks for multi-line text, but they do not interpolate: use an f-string (f"""...{x}...""") for that.

#01

A string across two lines

A triple-quoted string starts and ends with three double quotes and can contain real line breaks.

Print Line one and Line two on two lines using one triple-quoted string that spans both physical lines.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Keep a blank line

Inside a triple-quoted string, an empty physical line becomes an empty line in the output.

Print First, an empty line and Third using one string with three double quotes around it.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Quotes without escaping

Inside a triple-quoted string, a single " does not end the string, and ' needs no escaping either.

Print She said "hi" and it's fine using one string with three double quotes around it, and no backslashes.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Continue a line with a backslash

A backslash at the end of a line inside a normal string joins the next physical line into the same logical line. The newline and the backslash are removed.

Print This is a single line by writing the string across two physical lines with a backslash at the end of the first one.

Print exactly:

Create a free account to save your progress and unlock chapter 2.