How to define multiline strings?


Multiline Strings

A multiline string is a string that spans across two or more lines. In other words a string that has new lines.

To create or define a multiline string in Python, enclose the string value or literal in triple single quotes.

'''this is a
multiline string.
this is a sample
text.'''

We can assign this string value to a variable.

x = '''this is a
multiline string.
this is a sample
text.'''

Example

In the following program, we create a multiline string using triple quotes, and print it to console.

Python Program

x = '''this is a
multiline string.
this is a sample
text.'''
print(x)

Output

this is a
multiline string.
this is a sample
text.

Escape triple quotes inside a multiline string

Since we defined the string using triple single quotes, if we would like to use triple single quote inside this string, we must escape at least one single quote among the three single quotes using backslash character.

'''this is a
multiline string.\'''
this is a sample
text.'''

In the following program, we define a multiline string with a triple quote inside the string.

Python Program

x = '''this is a
multiline string.\'''
this is a sample
text.'''
print(x)

Output

sample" text

Summary

In this tutorial of Python Examples, we learned how to create a multiline string value using triple quotes.