How to create a long multi-line string in Python?


In this article, we are going to focus on how to create a long multiline string in Python.

The first approach is by using triple quotes, we should add a triple quote then we can add separate line inside the quotes, the multi-line string is created.

Using triple quotes in Python, it is possible to span strings across many lines. It can also be applied to lengthy code comments. Triple quotes can also contain special characters like TAB, verbatim, or NEWLINES. As the name would imply, the syntax consists of three single or double quotes placed consecutively.

Example

In the program given below, we are taking a multi−line string as input and we are printing it 

str1 ="""Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you
"""

print("The multi-line string is")
print(str1)

Output

The output of the above example is as shown below −

The multi-line string is
Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you

Using parenthesis

The second approach is by using parenthesis and multiple double quotes. We have to include the entire string inside the parenthesis and after completion of each line we should add new line character (\n) and add new line.

Example

In the example given below, we are taking a multi-line string by using parenthesis and printing it −

str1 =("Welcome to Tutorialspoint\n"
"How are you doing?\n"
"Hope everything is fine\n"
"Thank you")

print("The multi-line string is")
print(str1)

Output

The output of the above example is as shown below −

The multi-line string is
Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you

Using \ and newline character

The third approach is by using \ and newline character. This is similar to the above approach but we are not including the parenthesis we include \ after each new line character.

Example

In the example given below, we are taking a multi-line string by using parenthesis and printing it. −

str1 ="Welcome to Tutorialspoint\n"\
"How are you doing?\n"\
"Hope everything is fine\n"\
"Thank you"

print("The multi-line string is")
print(str1)

Output

The output of the above example is given below −

The multi-line string is
Welcome to Tutorialspoint
How are you doing?
Hope everything is fine
Thank you

Updated on: 07-Dec-2022

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements