05-12-2020, 07:19 AM
How to Do a Backslash in Python?
The Python backslash () is a special character that’s used for two purposes:
Try it yourself in our interactive Python shell (just click “Run”):
https://repl.it/@finxter/backslash?lite=true
The backslash is an escape character–if used in front of another character, it changes the meaning of this character. For example, the character is just that a simple character, but the character (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:
![[Image: grafik-15-1024x350.png]](https://blog.finxter.com/wp-content/uploads/2019/09/grafik-15-1024x350.png)
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:
![[Image: grafik-16-1024x284.png]](https://blog.finxter.com/wp-content/uploads/2019/09/grafik-16-1024x284.png)
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.
The Python backslash (
Code:
'\'- The Python backslash can be part of a special character sequence such as the tab character , the newline characterCode:
'\t', or the carriage returnCode:'\n'.Code:'\r'
- The Python backslash can escape other special characters in a Python string. For example, the first backslash in the string escapes the second backslash and removes the special meaning so that the resulting string contains the two charactersCode:
'\\n'andCode:'\'instead of the special newline characterCode:'n'.Code:'\n'
Try it yourself in our interactive Python shell (just click “Run”):
https://repl.it/@finxter/backslash?lite=true
The backslash
Code:
\Code:
'n'Code:
'\n'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:
![[Image: grafik-15-1024x350.png]](https://blog.finxter.com/wp-content/uploads/2019/09/grafik-15-1024x350.png)
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:
![[Image: grafik-16-1024x284.png]](https://blog.finxter.com/wp-content/uploads/2019/09/grafik-16-1024x284.png)
Code:
print('\\')
>>> \This is exactly what we want to accomplish. the first character
Code:
\Code:
\Code:
\
