How to Do a Backslash in Python?

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:

print('\\')
>>> \

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.

Leave a Comment

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