Python Forum

Full Version: Converting string to hex triplet
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Been racking my brain on how to convert string color to hex triplet.
Example convert gold to ffd700.
I know that for rgb this is ff(red) d7(green) 00(blue).

I can get the 8 bit hex and 16 bit hex values but, can't for the life of me figure out how to get the hex triplet. Any direction or guidance much appreciated.


My convert func for string to hex

def colors(color):
    color = color.encode('utf-8')
    hex_color = color.hex()
    print(hex_color)

# or using 16 bit

def colors(color):
    color = color.encode('utf-16')
    hex_color = color.hex()
    print(color)

colors('golden')
Output:
676f6c64656e #output 2 b'\xff\xfeg\x00o\x00l\x00d\x00e\x00n\x00'
Maybe webcolors can help

Quote:What this module supports
The mappings and functions within this module support the following methods of specifying sRGB colors, and conversions between them:
  • Six-digit hexadecimal.
  • Three-digit hexadecimal.
  • Integer rgb() triplet.
  • Percentage rgb() triplet.
  • Varying selections of predefined color names (see below).
What do you mean that "you can get the 8 bit hex"? It looks like your code is just converting each character of the word (like "golden") into a UTF-8 byte and then into a hex representation of it. So the character "g" will always be "67" in UTF-8. This has nothing to do with colors.

>>> "g".encode().hex()
'67'
Try the webcolors module.

>>> import webcolors
>>> webcolors.name_to_hex("gold")
'#ffd700'
In linux, there is a command showrgb that you could call from python
>>> import csv, subprocess
>>> p = subprocess.Popen('showrgb', stdout=subprocess.PIPE)
>>> database = list(csv.reader((x.decode() for x in p.stdout), delimiter='\t'))
>>> d = {x[-1]: tuple(int(y) for y in x[0].strip().split()) for x in database}
>>> d['orchid4']
(139, 71, 137)
PIL has a colormap dictionary.
from PIL import ImageColor

def print_color_info(name):
    color = ImageColor.colormap[name]
    print(f'{name} = {color}, RGB = {color[1:3]},{color[3:5]},{color[5:7]}')

print_color_info('red')
print_color_info('green')
print_color_info('blue')
print_color_info('orange')
print_color_info('yellow')
Output:
red = #ff0000, RGB = ff,00,00 green = #008000, RGB = 00,80,00 blue = #0000ff, RGB = 00,00,ff orange = #ffa500, RGB = ff,a5,00 yellow = #ffff00, RGB = ff,ff,00