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

Kent Johnson kent37 at tds.net
Tue Aug 26 03:31:20 CEST 2008


On Mon, Aug 25, 2008 at 8:45 PM, Py Hex <pyhex at yahoo.com> wrote:
> 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 ?

I think you are confusing representation with value. 0xCD and 205 are
different representations of the same value. The interpreter
understands both but the values are the same. In fact if you ask
Python for the value of e in your example, it will say it is 205.

The base (10 or 16) is a property of the representation, not the
value. The hex() function gives you the string representation of the
value as a (base 16) hex string. The str() function gives the standard
(base 10) string representation of an integer.

Are you just curious or is there something specific you are trying to do?

Kent


More information about the Tutor mailing list