Answers for "Converting Hex to RGB value in Python"

5

hex to rgb python

from colormap import rgb2hex
from colormap import hex2rgb

print(rgb2hex(255, 255, 255))
print(hex2rgb('#FFFFFF'))

>>> #FFFFFF
>>> (255, 255, 255)
Posted by: Guest on October-31-2020
1

hex to rgb python

def hex_to_rgb(hex_string):
    """Fastest Solution Universe
    
    >>> hex_to_rgb("#abc")
        (170, 187, 204)
    >>> hex_to_rgb("#ABC")
        (170, 187, 204)
    >>> hex_to_rgb("#aabbcc")
        (170, 187, 204)
    >>> hex_to_rgb("abc")
        (170, 187, 204)
    >>> hex_to_rgb("ABC")
        (170, 187, 204)
    >>> hex_to_rgb("aabbcc")
        (170, 187, 204)
    """
    str_len = len(hex_string)
    if hex_string.startswith("#"):
        if str_len == 7:
            r_hex = hex_string[1:3]
            g_hex = hex_string[3:5]
            b_hex = hex_string[5:7]
        elif str_len == 4:
            r_hex = hex_string[1:2] * 2
            g_hex = hex_string[2:3] * 2
            b_hex = hex_string[3:4] * 2
    elif str_len == 3:
        r_hex = hex_string[0:1] * 2
        g_hex = hex_string[1:2] * 2
        b_hex = hex_string[2:3] * 2
    else:
        r_hex = hex_string[0:2]
        g_hex = hex_string[2:4]
        b_hex = hex_string[4:6]

    return int(r_hex, 16), int(g_hex, 16), int(b_hex, 16)
Posted by: Guest on November-15-2021
0

Converting Hex to RGB value in Python

h = input('Enter hex: ').lstrip('#')
print('RGB =', tuple(int(h[i:i+2], 16) for i in (0, 2, 4)))
Posted by: Guest on March-13-2021

Python Answers by Framework

Browse Popular Code Answers by Language