Generating a Random Hex Color in Python


Question

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.

1
52
12/22/2012 12:25:45 AM

Accepted Answer

import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))
107
4/15/2013 8:36:31 AM

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)


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon