Skip to content

How to Convert a Hex String to RGB in Python

The challenge

When working with color values it can sometimes be useful to extract the individual red, green, and blue (RGB) component values for a color. Implement a function that meets these requirements:

  • Accepts a case-insensitive hexadecimal color string as its parameter (ex. "#FF9933" or "#ff9933")
  • Returns a Map<String, int> with the structure {r: 255, g: 153, b: 51} where rg, and b range from 0 through 255

Note: your implementation does not need to support the shorthand form of hexadecimal notation (ie "#FFF")


"#FF9933" --> {r: 255, g: 153, b: 51}
Code language: plaintext (plaintext)

The solution in Python code

Option 1:

def hex_string_to_RGB(s): return {i:int(s[j:j+2],16) for i,j in zip('rgb',[1,3,5])}
Code language: Python (python)

Option 2:

def hex_string_to_RGB(hex_string): r = int(hex_string[1:3], 16) g = int(hex_string[3:5], 16) b = int(hex_string[5:7], 16) return {'r': r, 'g': g, 'b': b}
Code language: Python (python)

Option 3:

from PIL import ImageColor def hex_string_to_RGB(hex_string): rgb = ImageColor.getrgb(hex_string) res = { 'r': rgb[], 'g': rgb[1], 'b': rgb[2] } return res
Code language: Python (python)

Test cases to validate our solution

@test.describe('Example Tests') def example_tests(): test.assert_equals(hex_string_to_RGB("#FF9933"), {'r':255, 'g':153, 'b':51}) test.assert_equals(hex_string_to_RGB("#beaded"), {'r':190, 'g':173, 'b':237}) test.assert_equals(hex_string_to_RGB("#000000"), {'r':, 'g':, 'b':}) test.assert_equals(hex_string_to_RGB("#111111"), {'r':17, 'g':17, 'b':17}) test.assert_equals(hex_string_to_RGB("#Fa3456"), {'r':250, 'g':52, 'b':86})
Code language: Python (python)

See also  MSSQL Select Not Null
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x