- Published on
Python — RGB To Hex Conversion
- Authors
- Name
- Jimmy Lai
RGB To Hex Conversion
The rgb function is deficient. Completing it will result in a hexadecimal representation being returned when RGB decimal values are passed in. RGB decimal values range from 0 to 255. Any values outside of that range must be rounded to the nearest valid value.
255, 255, 255 --> "FFFFFF"
255, 255, 300 --> "FFFFFF"
0, 0, 0 --> "000000"
148, 0, 211 --> "9400D3"
Note: answer should be 6 characters long, the shorthand with 3 will not work here. Examples (input --> output):
def rgb(r, g, b):
round = lambda x: min(255, max(x, 0))
return ("{:02X}" * 3).format(round(r), round(g), round(b))
def limit(num):
if num < 0:
return 0
if num > 255:
return 255
return num
def rgb(r, g, b):
return "{:02X}{:02X}{:02X}".format(limit(r), limit(g), limit(b))
def rgb(r, g, b):
return ''.join(['%02X' % max(0, min(x, 255)) for x in [r, g, b]])
def rgb(*args):
return ''.join(map(lambda x: '{:02X}'.format(min(max(0, x), 255)), args));
def rgb(r, g, b):
return "{:02X}{:02X}{:02X}".format(clamp(r), clamp(g), clamp(b))
def clamp(x):
return max(0, min(x, 255))
def rgb(r, g, b):
if r < 0:
r = 0
if g < 0:
g = 0
if b < 0:
b = 0
if r > 255:
r = 255
if g > 255:
g = 255
if b > 255:
b = 255
return '%02X%02X%02X' % (r,g,b)