Wednesday, February 21, 2024
HomeSoftware EngineeringFind out how to Convert a Hex String to RGB in Python

Find out how to Convert a Hex String to RGB in Python


The problem

When working with shade values it will probably typically be helpful to extract the person crimson, inexperienced, and blue (RGB) part values for a shade. Implement a operate that meets these necessities:

  • Accepts a case-insensitive hexadecimal shade 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 255

Notice: your implementation doesn’t have to help the shorthand type of hexadecimal notation (ie "#FFF")

Instance:

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

The answer in Python code

Choice 1:

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

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

Choice 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

Take a look at instances to validate our resolution

@take a look at.describe('Instance Assessments')
def example_tests():
    take a look at.assert_equals(hex_string_to_RGB("#FF9933"), {'r':255, 'g':153, 'b':51})
    take a look at.assert_equals(hex_string_to_RGB("#beaded"), {'r':190, 'g':173, 'b':237})
    take a look at.assert_equals(hex_string_to_RGB("#000000"), {'r':0, 'g':0, 'b':0})
    take a look at.assert_equals(hex_string_to_RGB("#111111"), {'r':17, 'g':17, 'b':17})
    take a look at.assert_equals(hex_string_to_RGB("#Fa3456"), {'r':250, 'g':52, 'b':86})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments