The “\n” is a newline special character called an escape character that moves the cursor to the beginning of the next line in text output. The “n“ is an escape sequence interpreted by Python to represent a line break.
To print the data in the console, we use the print() function. The print() function can be used in three ways, each of which helps us print a newline while outputting the text.
- Explicitly include “\n” in the print() function
- Implicitly add “\n” via the end parameter’s default value of the print() function
- Default Newline with print()
Explicitly include “\n” in the print() function
Embed \n in a string for manual newline control.
Single new line
print("This is a line of text.\nThis is a new line of text.") # Output: # This is a line of text. # This is a new line of text.
Multiple new lines
You can also use \n multiple times to add multiple empty lines or format your output as needed
print("This is a line of text.\n\nThis is a new line of text.") # Output: # This is a line of text. # This is a new line of text.
In the above code, we used two \n characters to create a blank line between the first and second lines.
Combining sep and newlines
You can use sep with \n for formatting multiple objects and printing them.
print("A", "B", "C", sep='\n') # Output: # A # B # C
Default Newline with print()
The print() automatically appends a newline (\n) unless end is modified.
Each print() call ends with \n, moving the cursor to a new line.
print("This is a line of text.") print("This is a new line of text.") # Output: # This is a line of text. # This is a new line of text.
If you want to add a blank line between two lines of text, use an empty print() statement.
print("This is a line of text.") print() print("This is a new line of text.") # Output: # This is a line of text. # This is a new line of text.
Suppressing the Newline
In print(), you can customize the “end” parameter, which you can use to suppress the default behaviour.
You can set end=” to prevent the automatic newline.
print("Hello", end='') print("World") # Output: HelloWorld
In the above code, since the end”” prints an empty character at the end of the first string, the cursor does not go to the second line. It stays right there and prints the second text on the same line.
Using sys.stdout.write()
If you are exploring a lower-level alternative, a sys package provides stdout.write() method that requires explicit “\n”.
import sys sys.stdout.write("Block\n") sys.stdout.write("Buster\n") # Output in the console: # Block # Buster
Writing to files
When you write to files, newlines are explicit.
with open("output.txt", "w") as f: f.write("Hello\nWorld")
Triple-quoted strings
You can use the triple quotes ”’ ”’ to support multi-line strings directly.
info = """Line A Line B Line C""" print(info) # Output: # Line A # Line B # Line C
That’s all!