Backslash and Raw Strings in Python

In this article, we would discuss how to use backslash and raw strings in Python. We will start with the backslash first and then in the section raw strings.

Backslash: There are certain characters which we can’t put in our string. Python wouldn’t recognize them the way we want it to. Therefore, we need to use an escape character to make Python process things for us as per our requirements.

In that scenario, we need to use an escape character like backslash \. The character we want to process is preceded by backslash. Let’s understand it with the help of an example.

Suppose we want the Python to process the following text –

x="How are "you"?"

You would notice that, we have put -you- in quotes. The Python Interpreter would throw a syntax error –

SyntaxError: invalid syntax

To overcome the issue, we need to use the backslash (\) –

x="How are \"you\"?"

Try this again, you would see everything would run clean this time around.

Now, do –

print(x)

Output –

"How are "you"?"

But, there are times when we want to keep the backslash along-with the following character. And, Python keeps treating the backslash as escape character. There’s a way around it. We use two backslashes. For instance –

x="backslash \newline example"
print(x)

The output of above code is –

backslash
ewline example

But, we want to process the above as a single line. Hence, we can use two backslashes –

x="backslash \\newline example"
print(x)

The desired output –

backslash \newline example

But, that is not the ideal approach. If there are multiple of those, then we would put backslash in-front of each of those.

That’s where Raw strings are preferred.

Raw strings: By using raw strings, we can completely eliminate the need to put backslash to escape a character. Continuing with the above example –

x=r'"How are "you"?"'
print(x)

We have used a prefix r. The output –

"How are "you"?"

Even if we use backslash somewhere in between the above string, it would treat it as a part of the string.

x=r'"How are \"you"?"'
print(x)

The output –

"How are \"you"?"

It is worth mentioning here that, the raw strings can’t end with a single backslash. But, if that is what we want then use two backslashes at the end of the raw string.

In conclusion, we have discussed backslash and raw strings in Python with examples.