How to write a string with new line in Python?
Python - Write string with new line
To write a string with new line in Python, write backslash followed by lower case n, \n, where ever you need a new line in the string.
\n character specifies new line, and when printing, the cursor moves to the new line, prints the characters after the new line character in a new line.
In this tutorial, we shall go through some examples where we write one or more new line characters in a string based on the use case.
1. Python string with one new line character
For example, consider the following string.
Hello
World!
In the above string, there is a new line right after the word "Hello"
. Therefore, we have to write the string with the new line character \n
as
"Hello\nWorld!"
Let us write a program where we take this string literal, and print it to standard output.
Python Program
print("Hello\nWorld!")
Output
2. Python string with multiple new line characters
Consider the following content, which is a string with new line characters at the end of the each sentence.
This is para 1.
This is para 2.
This is para 3.
How do we write the above content as a string in Python? We use the new line character \n
where required.
"This is para 1.\nThis is para 2.\nThis is para 3."
Let us write a program where we take this string literal, and print it to standard output.
Python Program
print("This is para 1.\nThis is para 2.\nThis is para 3.")
Output
Summary
In this tutorial, we have seen how to write a string with new line in Python, with examples covering scenarios where we write a new line character between two words, or we write three sentences which are separated by new line character.