How to escape from \n newline character in Python
This Python tutorial is all about how you can escape newline character from a string in Python.
If you are willing to print \n in Python it will create a new line instead of printing that as a string. Because of \n is known as a special character, a newline character.
So in this tutorial, our objective is to print \n as it is instead of creating a new line in Python programming. We will learn how to stop creating a new line while printing \n.
You may also be interested in knowing: how to escape quotes in python – escape quotes from string
Escape a newline character from a string
Let’s understand this with an easy example:
Assume that you have to print a path or directory location of your local drive.
The path is:
Now if you use the below code to print it out as a string:
You can see that a new line has appeared due to D:\Saruque\Pictures\new_pics
The \n appears in that string and \n creates a new line. So how to get rid of this \n?
Here is the solution.
D:\Saruque\Pictures\new_pics Process finished with exit code 0
Escape Any Special Character in a string in Python
There are many other special characters available in Python and you may also prevent them and print them as it is.
As you have seen \n creates a new line.
Here are a few special characters listed below:
\\ \a \b \f \r \t \ooo \xhh
There are more you can find out them on https://docs.python.org/2.0/ref/strings.html
So whenever this type of special character appears in the string that you are trying to print, errors may occur. You will not get your desired result unless you use something like this below:
The r before the first double quote will ignore the functionality of special characters and let you print whatever you want.