Generating a Random Hex Color in Python

little late to the party,

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

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

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'

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)

Tags:

Python

Django