[docs] discrepancy in result by hex()

Julien Palard julien at palard.fr
Sun Jul 7 17:11:14 EDT 2019


Hi Sunil,

> The hex() works fine overall but for numbers less than 16 it doesn't gives right output
> for e.g
> >>> hex(15)
> '0xf'
> where it should have been '0x0f'

Why?

0x0f is actually equal to 0xf as 01 is equal to 1 in decimal, I don't see any error here.

The hex function is not oriented toward working on bytes, take for exemple hex(999), it gives 0x3e7.

If you need to convert bytes to a fixed-width representation you can use f-strings or .format, like this:

>>> f"{x:#04x}"

For x == 6 it gives: '0x06'
For x == 60 it gives: '0x3c'
For x == 255 it gives: '0xff'

Bests,
-- 
Julien Palard
https://mdk.fr



More information about the docs mailing list