[Python-Dev] Extending hex() and oct() to accept strings

Matthew F. Barnes mfb at lotusland.dyndns.org
Wed Aug 27 19:09:35 EDT 2003


Forgive me if this idea has been already proposed and shot down.

Earlier today I was trying to print some binary data I received over a
socket in hexadecimal format so that I could decipher the contents.  The
first thing I instinctively tried was hex(datastring) and was somewhat
suprised to find that it didn't work.

I wandered around the documentation a bit looking for a simple and
"obvious" way to do this and came up empty (I would appreciate it if
someone could enlighten me if there already is a way).  For the rest of
the day it kinda bothered me that my first attempt didn't work.

After spending probably not enough time thinking about this, I came up
with what might be a reasonable extension for hex() and oct() that would
allow those functions to accept a string and produce a quoted hexadecimal
or octal representation of the input string using the escape notation \xhh
or \ooo.

To illustrate:

>>> hex('ABC')
"'\\x41\\x42\\x43'"
>>> print hex('ABC')  # This is what I was trying to do today
'\x41\x42\x43'
>>> eval(hex('ABC'))
'ABC'

>>> oct('ABC')
"'\\101\\102\\103'"
>>> print oct('ABC')
'\101\102\103'
>>> eval(oct('ABC'))
'ABC'

Are there any subtle issues with supporting this that I'm not seeing?

Matthew Barnes



More information about the Python-Dev mailing list