1

In Python 3 I am trying to make a set containing a backslash as an element:

a = {"/", "\"}

But I noticed that as soon as I closed the bracket after "\", the bracket became blue. I, learned that \ is an "escape" character used in things like \r, \t etc. But I want to take a backslash as a single piece of string. How to prevent this problem?

snakecharmerb
  • 36,887
  • 10
  • 71
  • 115
  • 3
    you can use the `r` string literal (`r"\"`) to tell Python not to interpret the backslash as an escape sequence, see also [this](https://stackoverflow.com/questions/2081640/what-exactly-do-u-and-r-string-flags-do-and-what-are-raw-string-literals). – FObersteiner Oct 31 '20 at 08:46

2 Answers2

2

You need to escape the \ by also using a backslash. Therefore you will need two \\

Your string will then become a={"/","\\"}

0

In Python strings, the backslash "" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. you can use this for \ and /:

>>> print('apple\torange')
apple   orange 
>>> print('apple\norange')
apple
orange 
>>> print('\\')
\
>>> print('/')
/
Salio
  • 773
  • 7
  • 17