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.")
You Want New Line
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)
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.
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.