How to Do a Backslash in Python?

5/5 - (2 votes)

The Python backslash ('\') is a special character that’s used for two purposes:

  1. The Python backslash can be part of a special character sequence such as the tab character '\t', the newline character '\n', or the carriage return '\r'.
  2. The Python backslash can escape other special characters in a Python string. For example, the first backslash in the string '\\n' escapes the second backslash and removes the special meaning so that the resulting string contains the two characters '\' and 'n' instead of the special newline character '\n'.

Try it yourself in our interactive Python shell (just click “Run”):

The backslash \ is an escape character–if used in front of another character, it changes the meaning of this character. For example, the character 'n' is just that a simple character, but the character '\n' (yes, it’s one character consisting of two symbols) is the new line character. We say that it is escaped.

So how do we define a string consisting of the backslash? The problem is that if we use the backslash, Python thinks that the character that follows the backslash is escaped. Here’s an example:

We want to print a string consisting of a single backslash, but the backslash escapes the end of string literal \’. Hence, the interpreter believes the string was never closed and throws an error.

The correct way of accomplishing this is to escape the escape character itself:

>>> \

This is exactly what we want to accomplish. the first character \ escapes the second character \ and therefore removes its meaning. The second character \ is therefore interpreted as a simple backslash.