Python - counting up in hex

For given int value, hex function will give you the hex string preceded with 0x, so hex(i)[2:] gives you the hex number itself, zfill will make sure you get two digits for the single digits numbers

for i in range(256):
    print(hex(i)[2:].zfill(2))

You might also want to consider making it all caps, since some parsers rely on hex being written in capital letters, so the example will be:

for i in range(256):
    print(hex(i)[2:].zfill(2).upper())

And if you just need the full string, you don't need to append them one by one, you can create the string in one go:

hex_str = "".join([hex(i)[2:].zfill(2).upper() for i in range(256)])

I guess you mean something like:

>>> for i in range(256):
    print "{:02x}".format(i)  # or X for uppercase


00
01
02
...
fd
fe
ff

Tags:

Python

Hex

Count