[Tutor] Why does the Hex builtin function in Python return a string ?

John Fouhy john at fouhy.net
Tue Aug 26 03:18:16 CEST 2008


2008/8/26 Py Hex <pyhex at yahoo.com>:
> When I run this:
>
>>>> type(hex(12))
> <type 'str'>
>
> I get a string type back, i.e, '0xC' not 0xC
>
> On the other hand, if I use 0x with data, Python understands it is hex data and not a string value.
>
>>>> e = 0xCD
>>>> type(e)
> <type 'int'>
>
> Why does the Hex builtin function in Python return a string ?  How can I convert this string returned by hex builtin function to data with 0x prefixed ?

If you type 0xC, you get a number.  Try it:

>>> 0xC
12

'12' is the default python representation of the integer 0xC.
Internally, it is (I guess) stored as a 4 byte chunk of memory; that
is, a 32-bit long binary.  There is _no difference_ between 0xC and
12:

>>> 0xC is 12
True

The hex() function (and oct() too) provides you with a different
string representation from the default.  If you want to change python
to display integers in hex instead of decimal by default, I can't help
you.. (well, maybe you could subclass int, and change __repr__ and
__str__ to return hex strings)

-- 
John.


More information about the Tutor mailing list