How to assign a multiline string to a variable in Python

Overview

A variable in Python is a reserved memory location used to store values. For example:

name = "Theo"

The name stands as a variable while "Theo" stands as the variable’s value.

From the code above, the variable name can also be explicitly called a string variable because the value assigned to it, Theo, is a string data type or value.

The string in the code is a single line string. What happens when we want to write two or three-string sentences?

Example

# trying to create the multiline string variable
composition = "Theo is a good boy.
His favorite food is fried rice and chicken.
He likes to plat basket ball as well as football"
# to return the multiline string variable
print(composition)

Output

SyntaxError: EOL while scanning string literal

Unfortunately, our code returned a SyntaxError and further read EOL while scanning string literal.

This means that the Python interpreter expects a character or set of sequence of characters to continue in that particular line of code. However, those characters or sequence of characters could not be found at “the end of the line” (EOL stands for end of line). For that reason, Python returns an error message.

A multiline string variable

To create a multiline string variable in a Python code, to avoid an error message, we enclose the multiline string in three single quotes ('''Multiline string''') or three double quotes (""" Multiline string""")

Example

# creating a correct multiline string
name = """Theo is a good boy.
His favorite food is fried rice with chicken.
He likes to play basketball as well as football."""
# to return the multiline string variable
print(name)

Summary

A multiline string in Python begins and ends with either three single quotes or three double quotes.

Free Resources