Adding or printing a new line in Python is a very basic and essential operation that can be used to format output or separate the data for better readability. Let's see the different ways to add/print a new line in Python
Using \n escape character
The \n is a escape character and is the simplest way to insert a new line in Python.
print("Hello\nWorld!")
Output
Hello World!
Explanation: Whenever \n is included in a string, it moves the cursor to the next line, hence adding/printing the rest of the output in a new line.
Using print() function with a new line
Using multiple print() statements to simply print a new line.
print("Hello")
print("World")
Output
Hello World
Explanation: The print() function in Python ends with a new line so we don't need to do anything to create a new line between print statements.
Adding new lines to Strings
We can concatenate multiple strings by using '\n' between them directly to include new lines.
a = "Hello" + "\n" + "World"
print(a)
Output
Hello World
Explanation: \n moves the cursor to the next line, thus printing whatever's left in the next line.
Using Triple Quotes
Using triple quotes( ' ' ' or " " ") allows us to include new lines directly in the string without using \n.
a = """Hello
World"""
print(a)
Output
Hello World
Explanation: Whenever we enclose a string in triple quotes any line breaks, tabs or spaces within the quotes are preserved as they are.
Using os.linesep for Platform Independence
The os.lineup constant provides us with the newline character that is specific to the operating system.
import os
# Add new lines using os.linesep
a = "Hello," + os.linesep + "This is a new line."
print(a)
Output
Hello, This is a new line.
Explanation: This code uses os.linesep to add a platform-specific newline between the strings "Hello," and "This is a new line.", and then prints the concatenated message.