How to create a random hexadecimal number in Python?

RavinDJ

Supreme [H]ardness
Joined
Apr 9, 2002
Messages
4,578
How to create a random hexadecimal number in Python?

I'm trying to create a random color and I would like the color to be in hexadecimal format (ie. #000000, #ffffff, or #55BBDD)

I know how to create a random number, but a random hex #? Any ideas?

Thanks!
 
just generate a random number 0-255 using whatever method python has, and then convert that number to hex using basic number system math (divide by 16 and use the remainder, etc)
 
Fryguy8 said:
just generate a random number 0-255 using whatever method python has, and then convert that number to hex using basic number system math (divide by 16 and use the remainder, etc)
in that case you'd need to generate 3 random numbers, since he wants a 3 byte long string.
 
Why not get a single random number from 0 to 0xFFFFFF?

Code:
import random
x = random.randint(0, 16777215)
print "#%x" % x
 
How about a random number based on system idle process + page file

overkill is nice...but u can't get more random than that can u?
 
I can't guess what you specifically mean by "based on system idle process + page file", but those things are easily observed and manipulated by another process, and so your random numbers are going to be predicted or influenced.

The random class in Python looks pretty good; why is it that you want to replace it?
 
Back
Top