How to turn decimals into hex without prefix `0x`
<pre><code>def tohex(r, g, b):
    #your code here :)
    def hex1(decimal):
        if decimal &lt; 0:
            return '00'
        elif decimal &gt; 255:
            return 'FF'
        elif decimal &lt; 17:
            return  '0'+ hex(decimal)[2:]
        else:
            return inthex(decimal)[2:]
    return (hex1(r) + hex1(g) + hex1(b)).upper()
print rgb(16 ,159 ,-137)
</code></pre>

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

<p>You have an extra zero because the line should be <code>elif decimal &lt; 16</code> not <code>17</code>.  </p>

<p>Use format strings<sup>1</sup>:</p>

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

print rgb(16,159,-137)
</code></pre>

<p>Output:</p>

<pre><code>109F00
</code></pre>

<p><sup>1</sup><a href="https://docs.python.org/2.7/library/string.html#format-specification-mini-language" rel="nofollow">https://docs.python.org/2.7/library/string.html#format-specification-mini-language</a></p>

python python-2.7 hex