Alex Thomson Alex Thomson - 1 year ago 199
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:]
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
instead of
. Why there is an extra 0?

Answer Source

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)




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download