Generating a Random Hex Color in Python

For a Django App, each "member" is assigned a color to help identify them. Their color is stored in the database and then printed/copied into the HTML when it is needed. The only issue is that I am unsure how to generate random Hex colors in python/django. It's easy enough to generate RGB colors, but to store them I would either need to a) make three extra columns in my "Member" model or b) store them all in the same column and use commas to separate them, then, later, parse the colors for the HTML. Neither of these are very appealing, so, again, I'm wondering how to generate random Hex colors in python/django.


import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))

Here is a simple way:

import random
color = "%06x" % random.randint(0, 0xFFFFFF)

To generate a random 3 char color:

import random
color = "%03x" % random.randint(0, 0xFFF)

%x in C-based languages is a string formatter to format integers as hexadecimal strings while 0x is the prefix to write numbers in base-16.

Colors can be prefixed with "#" if needed (CSS style)


Store it as a HTML color value:

Updated: now accepts both integer (0-255) and float (0.0-1.0) arguments. These will be clamped to their allowed range.

def htmlcolor(r, g, b):
    def _chkarg(a):
        if isinstance(a, int): # clamp to range 0--255
            if a < 0:
                a = 0
            elif a > 255:
                a = 255
        elif isinstance(a, float): # clamp to range 0.0--1.0 and convert to integer 0--255
            if a < 0.0:
                a = 0
            elif a > 1.0:
                a = 255
            else:
                a = int(round(a*255))
        else:
            raise ValueError('Arguments must be integers or floats.')
        return a
    r = _chkarg(r)
    g = _chkarg(g)
    b = _chkarg(b)
    return '#{:02x}{:02x}{:02x}'.format(r,g,b)

Result:

In [14]: htmlcolor(250,0,0)
Out[14]: '#fa0000'

In [15]: htmlcolor(127,14,54)
Out[15]: '#7f0e36'

In [16]: htmlcolor(0.1, 1.0, 0.9)
Out[16]: '#19ffe5'

little late to the party,

import random
chars = '0123456789ABCDEF'
['#'+''.join(random.sample(chars,6)) for i in range(N)]

This has been done before. Rather than implementing this yourself, possibly introducing errors, you may want to use a ready library, for example Faker. Have a look at the color providers, in particular hex_digit.

In [1]: from faker import Factory

In [2]: fake = Factory.create()

In [3]: fake.hex_color()
Out[3]: u'#3cae6a'

In [4]: fake.hex_color()
Out[4]: u'#5a9e28'