Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Do a Backslash in Python?
1
How to Do a Backslash in Python?

The Python backslash (
Code:
'\'
) 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
    Code:
    '\t'
    , the newline character
    Code:
    '\n'
    , or the carriage return
    Code:
    '\r'
    .


  2. The Python backslash can escape other special characters in a Python string. For example, the first backslash in the string
    Code:
    '\\n'
    escapes the second backslash and removes the special meaning so that the resulting string contains the two characters
    Code:
    '\'
    and
    Code:
    'n'
    instead of the special newline character
    Code:
    '\n'
    .


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

https://repl.it/@finxter/backslash?lite=true

The backslash
Code:
\
is an escape character–if used in front of another character, it changes the meaning of this character. For example, the character
Code:
'n'
is just that a simple character, but the character
Code:
'\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:

[Image: 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]
Code:
print('\\') >>> \

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

Users browsing this thread:
1 Guest(s)

Forum Jump: