How to escape from \n newline character in python

This Python tutorial is all about how easily 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.

Here in this tutorial, 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 newline character from a string in Python

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:

D:\Saruque\Pictures\new_pics

Now if you use the below code to print it out as a string:

print("D:\Saruque\Pictures\new_pics")

Output:

D:\Saruque\Pictures
ew_pics

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.

print(r"D:\Saruque\Pictures\new_pics")

Output:

D:\Saruque\Pictures\new_pics

Process finished with exit code 0

Escape Any Special Character in a string in Python

There are many special characters we can use in Python.

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 characters appears in your string that you are trying to print, errors may occur. You will not get your desired result unless you use something like this below:

print(r"any_string_you_wanna_print")

The r before the first double quote will ignore the functionality of special characters and let you print whatever you want.

Leave a Reply

Your email address will not be published. Required fields are marked *