Best Practice to Python Convert Hex Color to RGB – Python Tutorial

By | September 15, 2019

In web development, we often use hex color (#ff6600), however, we have to use rgb in may python application. In this tutorial, we will write a python function to convert a hex color to rgb.

python convert hex color to rgb

Convert hex color to rgb

def hex_to_rgb(value):
    value = value.lstrip('#')
    return list(int(value[i:i+2], 16) for i in (0, 2, 4))

value: [#]hex, such as #ff6600 or ff6600

return:[r, g, b]

How to use?

hex_color = '#ff0066'
print(hex_to_rgb(hex_color))
hex_color = 'ff0066'
print(hex_to_rgb(hex_color))

The hex color #ff6600 is: [255, 0, 102]

Leave a Reply

Your email address will not be published. Required fields are marked *