hex question

Dave Angel davea at ieee.org
Fri Jun 25 17:55:38 EDT 2010


Sneaky Wombat wrote:
> 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?
>
>
>   
You don't say what you do want.  Currently, you have a literal that 
describes four characters.  Were you trying for 7 ?  If so, try escaping 
the first backslash.
      h2 = '\\x0a\xa8\x19\x0b'

On the other hand, maybe you're really trying for four, and think that 
the first one is different than you intended.  It's not.   You have to 
realize that the interactive interpreter is using repr() on that string, 
and a string representation chooses the mnemonic versions over the hex 
version.  There are frequently several ways to represent a given 
character, and once the character has been stored, repr() will use its 
own judgment on how to show it.

For a simpler example,
   b = '\x41\x42c'
   b
will display  ABc

'x41' is just another way of saying 'A'.    And  '\0a' is just another 
way of saying '\n'  or newline.

DaveA




More information about the Python-list mailing list