Getting hex from rgb

How can I get hex from rgb in python?

For example I have the value rgb - 255, 0, 0. How can I get the value hex from it?

Author: attracim, 2020-11-10

4 answers

>>> from functools import reduce
>>> hex(reduce(lambda a, e: (a<<8) | int(e), '128, 19, 255'.split(', '), 0)).replace('0x', '')
'8013ff'
 1
Author: vp_arth, 2020-11-10 17:18:27
'#' + ''.join(hex(int(i))[2:] if i != '0' else '00' for i in "255, 0, 0".split(', '))
 1
Author: Victor VosMottor, 2020-11-10 18:56:55

Option 1:

rgb = "255, 128, 64"

#text = '#' + ''.join([f"{int(i):02x}" for i in rgb.split(',')])

print(text)

Option 2:

text = '#' + ''.join(map(lambda i: f"{int(i):02x}", rgb.split(',')))
 1
Author: Zhihar, 2020-11-10 19:00:53
r, g, b = map(int, "255,0,0".split(','))
hex(r << 16 | g << 8 | b)
 0
Author: Victor VosMottor, 2020-11-10 18:49:52