How To Print A New Line In Python

In this tutorial, you will learn to print a new line in Python.

In Python, all you need to do to print a new line is type ‘\n’ into the print function. The ‘\n’ function is the same as it is in other programming languages such as C++ and JAVA. It also prints a new line starting from the point where it is used.

Let’s look at the example code below to see how new lines in Python work and how you can use them in your own code.

How To Print A New Line In Python Code Examples

Below are a few code examples to print a new line In Python.

#Printing New Line using '\n'
print("You Want New Line\n From Here.")

Output:

You Want New Line
 From Here.
How To Print A New Line In Python

I was able to print half of the string on a new line, as you can see from the code above. This occurred when I used the ‘\n’ character in the Python print function.

Alternate Method To Print New Line In Python

In Python, you can use the linesep method from the OS library. The linesep method works similarly to ‘\n’, but if you want to write a new line in an open text file, it may not work similarly to ‘\n’; instead, on Windows, it will work as ‘\r\n’.

As a result, you must consider where you are using the linesep method and what your requirements are. Let’s look at some code examples for linesep below.

#importing OS library
import os

#Creating A line variable to Store String
line = "This is the Line after which" + os.linesep + "You Want New Line."

#Printing the Above Variable
print(line)

Output:

This is the Line after which

You Want New Line.

As you can see from the code above, linesep works very similarly to the ‘\n’ with only minor differences.

Wrap Up

I hope you have a good understanding of how to print a new line in Python. I’ve provided two methods for printing a new line for you to try. One method is to use ‘\n’, while another is to use the linesep method from the OS library.

If you know of a better method than the one discussed above, please let me know in the comments section and I will gladly add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. How To Downgrade Python
  2. Convert String To A List In Python
  3. Python User Input from Keyboard – input() function
  4. Fix: Python Is Not Set From Command Line Or npm Configuration
  5. How To Take Integer Input In Python 3

Leave a Comment