Converting Hex to RGB value in Python

You can use ImageColor from Pillow.

>>> from PIL import ImageColor
>>> ImageColor.getcolor("#23a9dd", "RGB")
(35, 169, 221)

I believe that this does what you are looking for:

h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))

(The above was written for Python 3)

Sample run:

Enter hex: #B4FBB8
RGB = (180, 251, 184)

Writing to a file

To write to a file with handle fhandle while preserving the formatting:

fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2, 4)) ))

Just another option: matplotlib.colors module.

Quite simple:

>>> import matplotlib.colors
>>> matplotlib.colors.to_rgb('#B4FBB8')
(0.7058823529411765, 0.984313725490196, 0.7215686274509804)

Note that the input of to_rgb need not to be hexadecimal color format, it admits several color formats.

You can also use the deprecated hex2color

>>> matplotlib.colors.hex2color('#B4FBB8')
(0.7058823529411765, 0.984313725490196, 0.7215686274509804)

The bonus is that we have the inverse function, to_hex and few extra functions such as, rgb_to_hsv.

Tags:

Python

Colors

Rgb