w3resource

Python: Convert a hexadecimal color code to its RGB components

Python String: Exercise-94 with Solution

Write a Python program to convert a hexadecimal color code to a tuple of integers corresponding to its RGB components.

  • Use a list comprehension in combination with int() and list slice notation to get the RGB components from the hexadecimal string.
  • Use tuple() to convert the resulting list to a tuple.

Sample Solution:

Python Code:

def hex_to_rgb(hex):
  return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)) 
print(hex_to_rgb('FFA501'))
print(hex_to_rgb('FFFFFF'))
print(hex_to_rgb('000000'))
print(hex_to_rgb('FF0000'))
print(hex_to_rgb('000080'))
print(hex_to_rgb('C0C0C0'))

Sample Output:

(255, 165, 1)
(255, 255, 255)
(0, 0, 0)
(255, 0, 0)
(0, 0, 128)
(192, 192, 192)

Flowchart:

Flowchart: Convert a hexadecimal color code to its RGB components.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to extract numbers from a given string.
Next: Write a Python program to convert the values of RGB components to a hexadecimal color code.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Python: Tips of the Day

What is the difference between Python's list methods append and extend?

append: Appends object at the end.

x = [1, 2, 3]
x.append([4, 5])
print (x)

Output:

[1, 2, 3, [4, 5]]

extend: Extends list by appending elements from the iterable.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

Output:

[1, 2, 3, 4, 5]

Ref: https://bit.ly/2AZ6ZFq