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

Alan Gauld alan.gauld at btinternet.com
Tue Aug 26 15:09:11 CEST 2008


"Py Hex" <pyhex at yahoo.com> wrote 

>>>> type(hex(12))
> <type 'str'>
> 
> I get a string type back, i.e, '0xC' not 0xC

Thats right because hex is a representation format.
The data (12 in this case) is stored in binary on the PC.
What you see as hex (or decimal or ocatal...) is just 
a string representation of the underlying binary data.

> 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'>

Close. Python understands the string of characters you 
typed is in hex format and interprets the string as an integer 
value which it stores in binary internally.

> How can I convert this string returned by hex builtin 
> function to data with 0x prefixed ? 

The 0x prefix is a string. The data is always in binary.
You cannot convert a number to anything (other than 
int-float etc) you can only change its string representation.

> Am I missing anything ? 

Yes, you are missing the underlying data representation 
within the machine. You need to distinguish clearly in your 
mind the difference between what is stored and what is 
displayed. The storage is always binary. The display is 
whatever format you ask for (with decimal as default)

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list