Python – 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.'''

Python Program

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

Output

sample" text

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.'''

Python Program

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

Output

sample" text