the reason: python string assignments accidentally change '\b' into '\x08' and '\a' into '\x07', why Python did this?

前端 未结 2 510
不知归路
不知归路 2020-12-11 01:28

Had two answers and some comments, mentioned another question, but all had not provided REASON, why Python did this changes? such as \'/b\' is \'/x08\' is just the result, b

相关标签:
2条回答
  • 2020-12-11 01:59

    Escape sequence \a, \b is equivalnt to \x07, \x08.

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

    You should escape \ itself to represent backslash literally:

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

    or use raw string literals:

    >>> r'\a'
    '\\a'
    >>> r'\b'
    '\\b'
    
    0 讨论(0)
  • 2020-12-11 02:18

    Your strings are being escaped. Check out the docs on string literals:

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

    This is a historical usage dating from the early 60s. It allows you to enter characters that you're not otherwise able to enter from a standard keyboard. For example, if you type into the Python interpreter:

    print "\xDC"
    

    ...you'll get Ü. In your case, you have \b - representing backspace - which Python displays in the \xhh form, where hh is the hexadecimal value for 08. \a is the escape sequence for the ASCII bell: try print "\a" with your sound on and you should hear a beep.

    0 讨论(0)
提交回复
热议问题