Alex Thomson Alex Thomson - 2 months ago 15
Python Question

How to turn decimals into hex without prefix `0x`

def tohex(r, g, b):
#your code here :)
def hex1(decimal):
if decimal < 0:
return '00'
elif decimal > 255:
return 'FF'
elif decimal < 17:
return '0'+ hex(decimal)[2:]
else:
return inthex(decimal)[2:]
return (hex1(r) + hex1(g) + hex1(b)).upper()
print rgb(16 ,159 ,-137)


I define a new method to get my hex numbers. But when it comes to (16 ,159 ,-137), I got
0109F00
instead of
019F00
. Why there is an extra 0?

Answer

You have an extra zero because the line should be elif decimal < 16 not 17.

Use format strings1:

def rgb(r,g,b):
    def hex1(d):
        return '{:02X}'.format(0 if d < 0 else 255 if d > 255 else d)
    return hex1(r)+hex1(g)+hex1(b)

print rgb(16,159,-137)

Output:

109F00

1https://docs.python.org/2.7/library/string.html#format-specification-mini-language

Comments