简体   繁体   中英

How to take "\" (backslash) as string and not as an "escape" character in python3?

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?

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

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

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('/')
/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM