How to convert colors between HEX and RGB in Python Python 06.10.2015

Using struct

import struct

def hex2rgb(rgb):
    return struct.unpack('BBB', rgb.decode('hex'))

def rgb2hex(rgb):
    return struct.pack('BBB',*rgb).encode('hex')

# hex2rgb('7BF5BE')
# > (123, 245, 190)
#
# rgb2hex((123, 245, 190)
# > '7bf5be'

Using colors.py

from colors import rgb, hex

# rgb to hex
str(rgb(123, 245, 190).hex)

# hex to rgb
tuple(hex('7BF5BE').rgb)

Invert color

hex('7BF5BE').invert()