hex question
Matt McCredie
mccredie at gmail.com
Fri Jun 25 17:11:22 EDT 2010
Sneaky Wombat <joe.hrbek <at> gmail.com> writes:
>
> Why is python turning \x0a into a \n ?
>
> In [120]: h='\x0a\xa8\x19\x0b'
>
> In [121]: h
> Out[121]: '\n\xa8\x19\x0b'
>
> I don't want this to happen, can I prevent it?
'h' is an ascii string. The ascii encoding for '\n' is the number(byte) 0x0A.
When you type '\x0a' you are entering the ascii code directly.
>>> hex(ord('\n'))
'0xa'
Python doesn't know that you entered the values using the '\xXX' syntax, it just
knows that the string contains a byte with that value. When it prints it back
out, it will print out the corresponding symbol.
Any character that has a reasonable ascii representation will show up as that
symbol when it (or its repr) is printed.
>>> "\x61\x62\x63\x64\x65\x66"
'abcdef'
If you are interested in printing the hex values, you could so something like
this:
>>> h = '\x0a\xa8\x19\x0b'
>>> for c in h:
... print "0x%02x" % ord(c),
...
0x0a 0xa8 0x19 0x0b
Matt
More information about the Python-list
mailing list