How to print a new line in Python
Want to print a new line in Python? This guide shows you methods, tips, real-world uses, and how to debug common errors.

To control text formatting in Python, you must print new lines correctly. This skill is fundamental for readable console output, logs, and structured text files.
You'll learn several techniques, from the \n character to the print() function's end parameter. You will also find practical tips, real-world applications, and common debugging advice.
Using the \n character
print("Hello\nWorld")--OUTPUT--Hello
World
The most straightforward method for creating a new line is using the newline escape character, \n. When Python's interpreter encounters this character sequence inside a string, it doesn't print it literally. Instead, it translates it into an instruction to move the cursor to the start of the next line.
This is precisely what happens in the example. The \n within the string "Hello\nWorld" splits the text, causing "World" to print on a new line directly after "Hello". It's a concise way to structure output from a single string without multiple print() calls.
Common newline techniques
Beyond the \n character, you can also manage new lines with the print() function's end parameter, triple-quoted strings, and multiple print() statements.
Using the end parameter in print()
print("First line", end="\n\n")
print("Second line")--OUTPUT--First line
Second line
By default, every print() call finishes by adding a single newline. The end parameter lets you override this behavior by specifying a different string to append instead of the default \n.
- In the example,
end="\n\n"tells the firstprint()statement to add two newlines, creating the blank line between the outputs. - You can also use it to suppress newlines entirely with
end='', which forces the next print output onto the same line.
Using triple quotes for multi-line strings
multi_line_string = """First line
Second line
Third line"""
print(multi_line_string)--OUTPUT--First line
Second line
Third line
Triple quotes, using either """ or ''', let you create strings that span multiple lines. Any line breaks you type inside the quotes are preserved exactly as they appear, becoming part of the string itself.
- This is especially useful for formatting long blocks of text or code snippets without needing to manually insert
\ncharacters.
When you print a variable containing a triple-quoted string, the output renders with all the original line breaks intact, just as you see in the example.
Multiple print() statements
print("Line 1")
print("Line 2")
print("Line 3")--OUTPUT--Line 1
Line 2
Line 3
The most intuitive way to print on separate lines is to simply call the print() function multiple times. Each statement executes in order, printing its argument and then automatically advancing to the next line before the next call.
- This approach is highly readable and works perfectly when you need to output a sequence of distinct lines or variables. It's a fundamental pattern for generating structured text output.
Advanced newline operations
As your programs grow, you'll need more sophisticated ways to manage newlines, which is where string formatting and methods like join() come into play.
Using string formatting with newlines
items = ["apple", "banana", "cherry"]
formatted_list = "Items:\n{}".format("\n".join(f"- {item}" for item in items))
print(formatted_list)--OUTPUT--Items:
- apple
- banana
- cherry
String formatting lets you dynamically build complex strings. In this example, a list of items is combined into a single, formatted block of text for clean output.
- First, a generator expression—
(f"- {item}" for item in items)—prepares each list item as a new string, prefixed with a dash. - Next,
"\n".join()connects these strings, inserting a newline character between each one to create a single multi-line string. - Finally, the
format()method places this resulting string into the"Items:\n{}"template, producing a neatly organized list.
Using join() with newlines
lines = ["Header", "-----", "Content", "Footer"]
text = "\n".join(lines)
print(text)--OUTPUT--Header
-----
Content
Footer
The join() method is a highly efficient way to build a single string from a list of strings. You call the method on the separator you want to use, which in this case is the newline character "\n".
- The method takes an iterable (like the
lineslist) as its argument. - It then connects every item from the list, inserting the
"\n"separator between each one.
This approach is perfect for assembling clean, multi-line text from various string parts without needing a loop.
Using platform-specific line endings
import os
text = "Line 1" + os.linesep + "Line 2"
print(text)--OUTPUT--Line 1
Line 2
Operating systems don't all agree on how to end a line. While systems like Linux and macOS use \n, Windows uses a different sequence, \r\n. This difference can cause formatting problems when you move text files between platforms.
- Python's
osmodule solves this withos.linesep. - This attribute automatically provides the correct line separator for the operating system your code is running on.
By using os.linesep instead of a hardcoded \n, you make your code more portable, ensuring consistent line breaks everywhere.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the newline techniques we've covered, from the basic \n character to the join() method, Replit Agent can turn them into production-ready tools.
- Build a command-line tool that generates formatted reports from raw data, using newlines to structure sections and lists.
- Create a text file organizer that reads, cleans, and rewrites files with consistent line endings using
os.linesep. - Deploy a simple ASCII art generator that converts text into styled, multi-line visual patterns.
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
Working with newlines can lead to subtle bugs, especially when dealing with file paths, cross-platform files, and multi-line string formatting.
Fixing escape sequence errors in file paths with \n
A common trip-up occurs with file paths, particularly on Windows. Since the backslash character (\) is used for both paths and escape sequences, a path like "C:\notes\file.txt" will fail because Python interprets \n as a newline. You can prevent this in a couple of ways.
- Use a raw string by prefixing it with an
r, liker"C:\notes\file.txt". This tells Python to ignore escape sequences and treat backslashes literally. - Use forward slashes (
/) instead. Python correctly translates them into the appropriate path separators on any operating system.
Handling different line endings when reading files
You might also face issues with files created on different operating systems. Because Windows uses a different line ending (\r\n) than macOS and Linux (\n), reading a text file across platforms can sometimes introduce unexpected blank lines or formatting errors. Python's file handling helps solve this. When you use the open() function in its default text mode, it automatically converts all incoming line endings to a standard \n. This feature, known as universal newlines, ensures your code behaves consistently regardless of the file's origin.
Managing indentation in triple-quoted strings
Finally, indentation can be a challenge with triple-quoted strings. Any whitespace you add to align a multi-line string with your code becomes part of the string itself, resulting in unwanted spaces at the beginning of each line. The best way to handle this is with the dedent() function from the textwrap module. It inspects the string, finds the minimum shared indentation, and removes it from every line—cleaning up your output while letting you keep your source code readable.
Fixing escape sequence errors in file paths with \n
Windows file paths can be tricky in Python because the backslash character (\) also creates escape sequences. When a path like C:\Users\name\notes.txt is written, Python interprets the \n as a newline character, which leads to unexpected errors. The following code demonstrates this problem.
file_path = "C:\Users\name\notes.txt"
print(f"Attempting to open: {file_path}")
with open(file_path, 'r') as file:
content = file.read()
The print() function reveals the problem. Python interprets the \n in the string as a newline before open() even runs, corrupting the file path and causing the operation to fail. The next example shows how to fix it.
file_path = r"C:\Users\name\notes.txt" # Using raw string
print(f"Attempting to open: {file_path}")
with open(file_path, 'r') as file:
content = file.read()
The solution is to use a raw string by adding an r prefix before the opening quote. This tells Python to treat backslashes as literal characters instead of escape sequences. As a result, \n is no longer interpreted as a newline, and the path r"C:\Users\name\notes.txt" is read correctly.
Keep an eye out for this issue whenever your code handles file paths, especially on Windows, as it’s a common source of hard-to-spot bugs.
Handling different line endings when reading files
When a file contains mixed line endings from different operating systems, manually splitting its content with split('\n') can introduce subtle bugs. You might get extra empty lines or strange characters in your output. The following code demonstrates this exact problem.
with open("mixed_line_endings.txt", 'r') as file:
lines = file.read().split('\n')
for i, line in enumerate(lines, 1):
print(f"Line {i}: {line}")
The split('\n') method only breaks text at the newline character. If a line ends with \r\n, the carriage return (\r) is left behind, corrupting the line's content. The following example shows a more robust approach.
with open("mixed_line_endings.txt", 'r') as file:
lines = file.read().splitlines()
for i, line in enumerate(lines, 1):
print(f"Line {i}: {line}")
The splitlines() method is the correct tool for the job. Unlike split('\n'), it automatically recognizes and handles all common line endings, including \n and \r\n. This ensures that each line is read cleanly without any leftover characters like carriage returns (\r).
You should always use splitlines() when reading text files, especially if they might come from different operating systems. It makes your code more robust and prevents subtle formatting bugs.
Managing indentation in triple-quoted strings
Triple-quoted strings are great for multi-line text, but they have a catch. Any indentation you use to align the string in your code becomes part of the string itself, leading to unwanted whitespace in your output. The following code demonstrates this problem.
def get_help_text():
help_text = """
Usage: program [OPTIONS]
Options:
--help Show this message
--version Show version
"""
return help_text
The help_text string inherits the indentation from the get_help_text function. This adds unwanted leading spaces to every line of the output, making the text look misaligned. The next example shows how to correct this formatting.
import textwrap
def get_help_text():
help_text = textwrap.dedent("""
Usage: program [OPTIONS]
Options:
--help Show this message
--version Show version
""")
return help_text
The solution is to use the textwrap.dedent() function. It intelligently removes the common leading whitespace from every line of your triple-quoted string. This cleans up the final output so it isn't indented, while still letting you keep the string neatly aligned in your source code. You'll find this especially useful when defining multi-line strings inside functions, classes, or other indented blocks to prevent unwanted formatting in the output.
Real-world applications
Mastering newlines lets you build practical tools, from scripts that generate simple receipts to programs that process complex, multi-line data files.
Creating a simple receipt with \n characters
You can combine f-strings with the \n character to build a clean, multi-line string that works perfectly for generating a simple receipt.
def print_receipt(items, prices):
total = sum(prices)
receipt = "==== RECEIPT ====\n"
for item, price in zip(items, prices):
receipt += f"{item}: ${price:.2f}\n"
receipt += f"===============\nTotal: ${total:.2f}"
return receipt
print(print_receipt(["Coffee", "Donut", "Newspaper"], [3.50, 2.25, 1.75]))
The print_receipt function dynamically constructs a multi-line string. It begins by initializing a receipt string with a header, then uses a loop to build the body.
- The
zip()function pairs each item with its corresponding price, allowing the loop to process them together. - Inside the loop, an f-string formats each line, and the
\ncharacter ensures each entry appears on a new line. - Finally, a footer with the calculated total is appended before the complete string is returned for printing.
Working with multi-line data processing
You can also use newlines to parse multi-line data, such as a block of CSV text, by splitting it into individual records for processing.
data = """name,age,role
John Doe,34,developer
Jane Smith,28,designer
Bob Johnson,42,manager"""
lines = data.strip().split('\n')
headers = lines[0].split(',')
result = []
for line in lines[1:]:
values = line.split(',')
person = dict(zip(headers, values))
result.append(f"{person['name']} is a {person['role']}, age {person['age']}")
print('\n'.join(result))
This code demonstrates a powerful way to restructure text data. After splitting the initial string into lines, it uses the first line as headers. The real magic happens inside the loop.
- The
zip()function pairs each header (like"name") with a value from a data line (like"John Doe"). dict()then converts these pairs into a dictionary, making the data easy to access by key.- An f-string then pulls values from this dictionary to build a new sentence, and
'\n'.join()prints each sentence on its own line.
Get started with Replit
Turn these techniques into a real tool. Describe what you want to build, like “a script that formats CSV data into a clean report” or “a tool that generates a formatted receipt from a list of items.”
Replit Agent writes the code, tests for errors, and deploys your app for you. Start building with Replit and bring your ideas to life.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)