In this Answer, we are going to see how we can convert any hexadecimal color code value to its RGB format equivalent and vice-versa. Let’s see them one by one.
We will use the following approach to convert hex color codes into RGB format:
Let’s see how this can be implemented in the code.
def hex_to_rgb(hex):rgb = []for i in (0, 2, 4):decimal = int(hex[i:i+2], 16)rgb.append(decimal)return tuple(rgb)print(hex_to_rgb('FFA501'))
Explanation
hex_to_rgb()
function that accepts the hex color code values.int()
function.Now, let’s see how we can convert the RGB values to their hex representation.
To convert RGB values to hex values, we are going to take the three RGB values and convert them to their hex representation using :02x
while returning the hex value.
Now, let’s take a look at the code.
def rgb_to_hex(r, g, b):return '#{:02x}{:02x}{:02x}'.format(r, g, b)print(rgb_to_hex(255, 165, 1))
Explanation
Line 1: A function named rgb_to_hex
is defined with three arguments r
, g
, and b
.
Line 2: The function returns a string in the format #RRGGBB
where RR
, GG
, and BB
are the hexadecimal representation of r
, g
, and b
respectively. The format
method is used to construct the string with :02x
specifying that the values should be formatted as two-digit hexadecimal numbers with leading zeros added if necessary.
Line 4: The line print(rgb_to_hex(255, 165, 1))
calls the rgb_to_hex
function with the arguments 255
, 165
, and 1
and prints the result #ffa501
.
Free Resources