简体   繁体   中英

Why are certain hexadecimal escape characters not displayed in python 3 unless the print statement is used?

I am learning about strings and bytestrings in python. I don't understand why certain hexadecimal escape sequences are displayed in \\XNN form and some are not?

s = 'A\x31\tC'
s1 = 'A\x00B\tC'

In this case, when I type s1 into the console, it prints the exact string of characters within the quotes,'A\\x00B\\tC', but when I type s into the console, it prints 'A1B\\tC'. It is only when I print s1 that the screen shows 'AB C'. I don't understand why certain escape characters are shown and others are not? And why does it then show when you print them?

Cheers

http://www.asciitable.com/

If you look at the ASCII table, you would see that some characters are printable, while others are not.

In particular, \\x31 == 1 (Hexadecimal 31 == Decimal 49 == ASCII Character 1 .

On the other hand \\x00 is not printable. It represents the null terminator (or \\0 )

>>> '\x31' == '1'
True
>>> '\x00' == '\0'
True

A more interesting question is: Why does \\x31 get converted to 1 , \\x09 gets converted to a \\t , while \\x00 is not converted to \\0 . That I don't know.

When you type name into the interpreter, it is using the result of calling repr on that name. Since \\x31 can be represented as 1 , it uses that. Since \\x00 cannot be represented as a printable character, it falls back to using the hex escape notation.

Note that:

>>> '\x31' == '1'
True

So the result of repr is valid.

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