Tips on how to Convert a Hex String to RGB in Python

0
11
Adv1


Adv2

The problem

When working with coloration values it may generally be helpful to extract the person pink, inexperienced, and blue (RGB) part values for a coloration. Implement a operate that meets these necessities:

  • Accepts a case-insensitive hexadecimal coloration string as its parameter (ex. "#FF9933" or "#ff9933")
  • Returns a Map<String, int> with the construction {r: 255, g: 153, b: 51} the place rg, and b vary from 0 by means of 255

Word: your implementation doesn’t must assist the shorthand type of hexadecimal notation (ie "#FFF")

Instance:

"#FF9933" --> {r: 255, g: 153, b: 51}

The answer in Python code

Possibility 1:

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

Possibility 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}

Possibility 3:

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

Check circumstances to validate our answer

@check.describe('Instance Checks')
def example_tests():
    check.assert_equals(hex_string_to_RGB("#FF9933"), {'r':255, 'g':153, 'b':51})
    check.assert_equals(hex_string_to_RGB("#beaded"), {'r':190, 'g':173, 'b':237})
    check.assert_equals(hex_string_to_RGB("#000000"), {'r':0, 'g':0, 'b':0})
    check.assert_equals(hex_string_to_RGB("#111111"), {'r':17, 'g':17, 'b':17})
    check.assert_equals(hex_string_to_RGB("#Fa3456"), {'r':250, 'g':52, 'b':86})
Adv3