By Arun Kumar
In this short tutorial, we look at how to add a Python new line. We look at the Python new line character and how the other methods can be used.
n programming, it is a common practice to break lines and display content in a new line. This improves the readability of the output. Apart from that, you would frequently come across the new line character a lot while working with files.
Hence it is quite important that you understand how to add a new line and familiarise yourself with how the new line character works. This tutorial is aimed to do the same.
In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.
As aforementioned, the character after the new line character is printed in a new line.
Different ways to implement this would include either adding it to string directly, or concatenating it before printing it. A common question that beginners have while learning how to apply a new line is - since we are adding it to a string - Why doesn’t Python print “\n” as it is? And how does it know that a new line must be added?
Well, the backslash (“\”) in the new line character is called an escape sequence. Escape sequences are used to add anything illegal to a string. This way Python understands that the following character is not a part of a string and executes it.
Multiline strings are another easy way to print text in a new line. As the name suggests the string itself spans over multiple lines. These strings can be assigned by using either 3 double quotes or 3 single quotes. Python understands that the string is a multiline string and prints it as such.
In the above example, the string is printed in the same way as the information was passed.
Although both methods can be used in Python to add new lines I would recommend using the first method as it is the most commonly accepted method. Also, given Python has an in-built character that facilitates this it is best to utilize it.
However, please feel free to explore and understand how the multiline method works.