Reason: python string assignments accidentally change '\ b' to '\ x08' and '\ a' to '\ x07', why did Python do this?

There were two answers and some comments mentioned, another question, but all did not provide REASON, why did Python do this? such as '/ b' is '/ x08' is only a result, but why? Greetings.

I am trying to add this path "F: \ large data \ Python_coding \ diveintopython-5.4 \ py" Thus, in sys.path, the code under it can be imported directly.

after use: sys.path.append('F:\big data\Python_coding\diveintopython-5.4\py')

I found that I had this path inside sys.path: 'F: \ x08ig data \ Python_coding \ diveintopython-5.4 \ py'

Then I tested using the following code: mypath1='F:\big data\bython_coding\aiveintopython-5.4\ry'

mypath1 now: 'F:\x08ig data\x08ython_coding\x07iveintopython-5.4\ry'

all '\ b' replaced by '\ x08' and '\ a' changed to '\ x07'

I searched for a while, but still can’t find the reason, could you check it and any feedback or help will be assigned. Many thanks.

+8
python string
source share
2 answers

Your lines are running. Check out the docs for string literals :

The backslash character () is used to remove characters that would otherwise have special meaning, such as a new line, backslash, or quote character. String literals may optionally be prefix with the letter r' or R'; such strings are called raw strings and use different rules for backslash escape sequences.

This is a historical use since the early 60s. It allows you to enter characters that you otherwise cannot enter from the standard keyboard. For example, if you enter a Python interpreter:

 print "\xDC" 

... you get Ü . In your case, you have a \b backspace view that Python displays in the form \xhh , where hh is the hexadecimal value for 08. \a is the escape sequence for an ASCII call: try print "\a" with your sound, and you should hear a beep.

+10
source share

The output sequence \a , \b equivalent to \x07 , \x08 .

 >>> '\a' '\x07' >>> '\b' '\x08' 

You should avoid \ to represent a backslash literally:

 >>> '\\a' '\\a' >>> '\\b' '\\b' 

or use string literals:

 >>> r'\a' '\\a' >>> r'\b' '\\b' 
+7
source share

All Articles