How to Line Break in Python?
In Python, line breaks are an essential part of formatting text output and ensuring that your code is readable and clean. Line breaks properly can make a huge difference in the clarity and functionality of your code.
In this guide, we will walk you through different ways to create line breaks in Python. Letâs explore the most common methods:
Line Breaks in Strings
Using \n
Escape Character
The simplest way to introduce a line break in Python is by using the \n
escape character. This tells Python to move the cursor to the next line wherever it appears in a string.
Example:
print("Hello\nWorld!")
Output
Hello World!
In this example, the \n inside the string creates a line break between "Hello" and "World!"
Using Triple Quotes for Multi-line Strings
If you want to create a string that spans multiple lines, Python allows you to use triple quotes (''' or """) to define multi-line strings. This is especially useful when working with long text blocks or when formatting code cleanly.
Example:
s = '''This is a
multi-line string.
Python makes it easy!'''
print(s)
Output
This is a multi-line string. Python makes it easy!
Let's take a look at other cases of line break in python:
Table of Content
Line Breaks in print() Function
Using print() with Multiple Arguments
You can use the print() function in Python to print multiple strings on different lines without explicitly using \n. By default, the print() function adds a line break after each call.
print("Hello")
print("World!")
Output
Hello World!
Each print() statement outputs the string followed by a new line, so you donât need to manually insert a \n.
Using print() Function with end
By default, the print() function in Python ends with a newline character (\n). If you wanted a custom line break, you could set the end argument to a newline or any other separator.
print("Hello", end="\n\n") # Two line breaks after "Hello"
print("World")
Output
Hello World
Writing/Reading Line Breaks in Files
If you're working with files, you can use the write() method to add line breaks when saving text. Unlike print(), write() does not automatically add a newline at the end, so you need to manually include the \n if you want a line break.
with open("example.txt", "w") as file:
file.write("Hello\nWorld\nPython\n")
This code will create a file example.txt
with the following contents:
Hello
World
Python
When reading files, Python automatically handles line breaks when using the readlines() method. Each line is stored as a string with its newline character \n still intact. You can remove the newline character by using the strip() method.