How to Print a New Line in Python: A Beginner-Friendly Guide

In Python, you can use the \n character to represent a new line. When you include \n in a string, Python will interpret it as a new line character and start the next part of the string on a new line.

Example:

print("Hello\nWorld!")

Output:

Hello
World!

As you can see, the \n character separates the words “Hello” and “World!” onto two different lines.

You can include multiple \n characters in a single string to add more than one line break:

print("Line 1\n\nLine 3")

Output:

Line 1

Line 3

Note: By default, the print() function adds a new line character at the end of each printed string. So, if you want to print content on separate lines, you can also simply use multiple print() statements.

Combiningย \nย with Other Characters

The \n character can be combined with other characters in a string to create more complex formatting. You can include text, numbers, or other escape characters alongside \n. Here are a few examples:

print("Name:\nJohn Doe")
print("Fruits:\n- Apple\n- Banana\n- Orange")
print("Greeting:\n\tHello, world!")

Output:

Name:
John Doe
Fruits:
- Apple
- Banana
- Orange
Greeting:
	Hello, world!

In the first example, we used \n to start a new line after the label “Name:”. In the second example, we used \n in combination with hyphens to create a simple list of fruits. In the third example, we used \n followed by the tab escape character \t to create an indented line.

Alternative Method: Using Triple Quotes

Python allows you to create multi-line strings using triple quotes (""" or '''). When you enclose a string in triple quotes, you can include new lines directly in the string without using the \n character. Here’s an example:

print("""This is a
multi-line string.
It spans across
multiple lines.""")

Output:

This is a
multi-line string.
It spans across
multiple lines.

This method is particularly useful when you need to print a large block of text with multiple lines.

That’s for it for this article, see you.

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *