I'd like to convert a hex triplet to an RGB tuple and then convert a tuple to a hex triplet.
A HEX color is expressed as a six-digit combination of numbers and letters defined by its mix of red, green and blue (RGB). Basically, a HEX color code is shorthand for its RGB values with a little conversion gymnastics in between. No need to sweat the conversion.
Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.
>>> import struct >>> rgbstr='aabbcc' >>> struct.unpack('BBB',rgbstr.decode('hex')) (170, 187, 204)
and
>>> rgb = (50,100,150) >>> struct.pack('BBB',*rgb).encode('hex') '326496'
Trying to be pythonic:
>>> rgbstr='aabbcc' >>> tuple(ord(c) for c in rgbstr.decode('hex')) (170, 187, 204) >>> tuple(map(ord, rgbstr.decode('hex')) (170, 187, 204)
and
>>> rgb=(12,50,100) >>> "".join(map(chr, rgb)).encode('hex') '0c3264'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With