Converting a RGB color tuple to a six digit code, in Python

rectangletangle picture rectangletangle · Aug 1, 2010 · Viewed 92.3k times · Source

I need to convert (0, 128, 64) to something like this #008040. I'm not sure what to call the latter, making searching difficult.

Answer

Dietrich Epp picture Dietrich Epp · Aug 1, 2010

Use the format operator %:

>>> '#%02x%02x%02x' % (0, 128, 64)
'#008040'

Note that it won't check bounds...

>>> '#%02x%02x%02x' % (0, -1, 9999)
'#00-1270f'