How to Print a Newline in Python? With Examples

How to Print a Newline in Python? With Examples

When we work with strings or text data, it often involves printing a new line. Generally, we use the print statement to print a string and another print statement to print it in a new line. After execution, when we write the print statement, the cursor automatically shifts to a new line. However, if we keep on writing new print statements repeatedly for every string, the code will become unclear and absurd. 

Hence, we use the escape character ‘\n’ to print a newline in Python. In this blog, we will discuss the different ways to print a new line, along with some examples. 

Print a Newline Using the \n Escape Sequence

In Python, an escape sequence is a special character, providing a simple and common way to print a newline by using a backslash (\). It represents a certain character or behavior. Using escape sequences, we can include characters in a string that are difficult to type directly into the code. 

We use escape sequences to add Python newline characters (\n) to a string. A newline character represents the end of a text line and causes the next character to be printed on a new line. 

So, when a string has a newline character, Python will start a new line in the output. It is used to format text in a program or create multi-line strings. 

Let’s understand this method through its functions, syntax, and more.

Character

‘\n’

Purpose

To shift the cursor to a new line.

Features

  • It is an escape sequence character.
  • It is valid for strings and characters only.
  • It is also known as line-break.
  • We can add ‘\n’ anywhere in a string.

Syntax

1. Declare a string in multiple lines

Str_var = "\nstring 1\n string 2\n"  

2. Print a string in multiple lines

print ("\nstr1\nstr2\n")  

Initial \n- It leaves a blank line and shifts to a new line, printing str1.

Middle \n- It prints str1 and then shifts to a new line, printing str2.

Final \n- After executing str2, it leaves a blank line and shifts to a new line.

Also read: Python Developer Roadmap (2024 Guide for Beginners)

Why do we need ‘\n’?

If you want to print “Hello”, “My”, and “Friends” in three different lines, you will do it using the normal print statement as shown below:

Code 

print ("Hello")  
print (“My”)  
print ("Friends")

Output

Hello
My
Friends

So, you would require 3 lines of code to print these words. It is a longer process and may not be useful for printing more strings. Therefore, we use ‘\n’ as shown in the following code:

print ("Hello\nMy\nFriends")  

Output

Hello
My
Friends 

Here, you need to write one line of code to print a new line in Python. You can use ‘\n’ to print any number of strings in multiple lines while keeping the code precise and simple. 

More About ‘\n’

Many wonder how Python recognizes ‘\n’ and why the print statement doesn’t print ‘\n’ like a normal string. Well, Python has a few predefined characters succeeding a backslash (\), known as the escape sequences. Python easily recognizes ‘\’, understands it’s not part of a string, and executes it according to the succeeding character. 

When we use a backslash before a character, the character can escape the normal string execution. A few examples of these characters are \t, \r, \n, etc.

Example– Declaring a string with ‘\n’

message = "Hello\nPython\nWorld"
print(message)

Output:

Hello
Python
World

Print a Newline Using the print() Function 

We can also use the print() function with the end parameter to print a newline character in Python. End is an optional parameter that mentions the last character with which to end the string. 

By default, this method adds a newline character at the end of the output, but to change this behavior, we specify a different string used as the end parameter. 

Example

print("Hello", end=" ")
print("Python", end=" ")
print("World")

Output:

Hello Python World

The print() function used with the end parameter enhances code readability, making it clearer where to add the newline character. However, it can make the code complicated and verbose, especially when it contains lengthy text blocks. 

Print a Newline Using the join() Method with the split() Method

Another way is to use the join() method with the split() method. It is an advanced way to print a newline character in Python. split() divides a string into substrings that are based on the specified separator. join() is used to join elements of a list into a single string. When we split a string on the newline character and join it back with a newline character separator, it allows us to print multiple lines of text. 

Example

# Original string with spaces as separators
text = "Hello Python World"
# Split the string into a list of words
words = text.split(" ")
# Join the words using a newline character (\n)
result = "\n".join(words)
print(result)

Output:

Hello
Python
World

Combining join() and split() makes the code clearer and more concise, improving code readability. However, printing multiple lines of text while working with lengthy blocks of text may not prove to be an effective method. 

Also read: Top 21 Python Developer Skills You Must Have in 2024

Print a String in a New Line 

This is another method to shift a string to a new line. We first use multiple print statements. We can also use the ‘\n’ character. To achieve this, we use multi-line strings. Single or double quotes are used to print a single-line string. To print multiple lines of strings, we use 3 single quotes (”’ string”’) or 3 double quotes (“””strings”””). 

Syntax

'''''String 1 
String 2 
............... 
String n'''  
  
OR  
  
"""String 1 
String 2 
.............. 
String n""" 

Python can recognize that a string is a multi-line string through single quotes or double quotes. 

Example

# Using triple double quotes to declare a multi-line string
multi_line_string = """This is line A
This is line B
This is line C"""

# Printing the multi-line string
print(multi_line_string)

Output:

This is line A
This is line B
This is line C

The Effect of the Newline Characters on Code

There are different studies investigating the effect of newline characters on code maintainability and readability. According to a study, it is easier to read and understand code with consistent and predictable newline characters, which is beneficial for beginners. Also, inconsistent use of indentation or whitespace or excessive use of newline characters can make the code harder to read and understand. Therefore, we must use the newline character consistently and predictably, following the guidelines and conventions of Python programming. 

FAQs- Print a Newline in Python

1. How do you print \n in Python?

In Python, ‘\n’ denotes a newline character that is used to print a new line. The print() function automatically adds a new line character at the end of the output. To change this, we need to set the end keyword argument to an empty string. 

2. What is a newline character in Python?

A Python newline character is represented by the special escape character ‘\n’, which indicates the end of a line of text and the beginning of a new one.

3. How to remove a newline in Python?

We can use various ways to remove a newline in Python. Let’s see the two commonly used methods:

Using strip() method

The strip() method is an in-built function in Python and is the easiest way to remove newline characters and trailing spaces from a string. As we use this function, we check for ‘\n’ as a string in a string. This method returns a copy of the original string, removing all the leading and trailing whitespace.

Using split() and join()

We can remove newline characters from a string using the split() and join() methods. split() is used to split the original string into a substring list based on the given delimiter. The join() method concatenates substrings to create a string and effectively removes the newline characters. 

 Conclusion

Now that you have explored the Python newline character, it’s time to use it in your code to make it easier to read and understand. It will be specifically useful for code with multiple lines or long strings. Moreover, it helps you avoid the pitfalls of writing multiple print statements for every string. To acquire Python skills and become a professional coder, take our Python online course that aims to take your proficiency to the next level.