Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a Random Hex Color in Python

Tags:

python

django

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.

like image 226
sinθ Avatar asked Dec 22 '12 00:12

sinθ


People also ask

How do I generate a list of random colors in python?

Given colour = [ "red", "blue", "green", "yellow", "purple", "orange", "white", "black" ] generate and print a list of 50 random colours. You will need to use the random module to get random numbers. Use range and map to generated the required amount of numbers. Then use map to translate numbers to colours.

How do you create a color in python?

In the RGB color model, any color can be generated by mixing 3 primary colors, namely, Red, Green, and Blue. In this model, a color can be described by specifying a group of 3 numeric values (typically ranging from 0 to 255), each specifying the intensity of Red, Green, and Blue colors present in a given color.


1 Answers

import random r = lambda: random.randint(0,255) print('#%02X%02X%02X' % (r(),r(),r())) 
like image 172
Dmitry Dubovitsky Avatar answered Oct 11 '22 07:10

Dmitry Dubovitsky