The Python backslash (
'\') is a special character that’s used for two purposes:
- 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
- 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
'n'instead of the special newline character
Try it yourself in our interactive Python shell (just click “Run”):
\ 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.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.