Reputation: 309
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
Upvotes: 1
Views: 500
Reputation: 3664
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.
Upvotes: 2
Reputation: 1565
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.
Upvotes: 2