Odd problem with converting string to Hex?

Remco Gerlich scarblac at pino.selwerd.nl
Thu Jul 5 02:50:38 EDT 2001

Benjamin Schollnick <junkster at rochester.rr.com> wrote in comp.lang.python:
> I haven't tried this.... But it certainly makes sense...
> I was assuming, incorrectly it appears, that Python was storing it 
> as a string of 3 or so characters.... After all, that's what the 
> Print command was displaying....

No, it didn't. The interpreter showed it, but not with the print command!

Try it:

>>> x = '\x00\x90\x83H\x11\x0f'
>>> x
>>> print x
          # In my xterm this prints the actual bytes, leaving nothing visible
>>> len(x)
>>> len(repr(x))
23     # Includes the '' around the string, the escaping, etc 

'\x00' is a length 1 string, containing a single character, hex 0.

The interactive interpreter uses repr() to show the value of things by
default, which returns a form that could be used as a Python literal. It
needs to escape things again. As an example: chr(92) is a backslash... try

>>> chr(92)
>>> print chr(92)

> I had never considered that it was being stored as a "list of 
> characters", array, or whatever you'd like to call it....
> Although, I want to stress STR(data....), didn't give a HEX PRINTABLE
> result....

You need to explain this, no idea what you mean. str() of a tuple calls
repr() again on the internal elements, so it has to returns the escaped
forms again.

Remco Gerlich

More information about the Python-list mailing list