create random hex color code using python

Today we are going to learn how to generate hex color code using python. Nowadays the hex color code is very useful in any designing part. In CSS part color is used as RGB and Hex code format. It is very easy to create/generate any random hex value in python. In this article, we covered Hex code generate.

Let’s go for the coding section:

Random hex Color code generate in python


  • random library


import random
random_number = random.randint(0,16777215)
hex_number = str(hex(random_number))
hex_number ='#'+ hex_number[2:]
print('A  Random Hex Color Code is :',hex_number)


A Random Hex Color Code is : #d68637


In this code at first, we import the random library to work.

Then we generate a random integer decimal number by using random.randint() function, which must be in between lower value 0 and upper value  16777215.

Then we convert the decimal number into hexadecimal value. And we convert the data type of the hexadecimal value into a string data type to perform any string operations.

As we know in python, after conversion any int value into hexadecimal, its starts with 0x in the hexadecimal value, to remove 0x, we take the string value after 2nd position.

Finally, we get a Hex code. Then simply we add a ‘#’ character at the beginning of the hex code. And Print it.

To generate random RGB color code read this:


An alternative way, without performing string operation in hex code


import random

random_number = random.randint(0,16777215)
hex_number =format(random_number,'x')
hex_number = '#'+hex_number
print('A  Random Hex Color is :',hex_number)


A  Random Hex Color is : #75a70c

Tricks: Here we use format(number,’x’) to convert the int decimal value to hexadecimal value. The benefit of this function is, this function will return the hex value without adding 0x at the beginning of the result.


You may like to read:

3 responses to “create random hex color code using python”

  1. Mary says:

    How do you apply this to objects, I am trying to assign random color to trees for a project

  2. Eskil Darpe says:

    Actually it should look like this:

    random_number = random.randint(1118481,16777215)
    hex_number = str(hex(random_number))
    hex_number = ‘#’+ hex_number [2:]

    Otherwise there can be incorrect color codes.

  3. Kunal Tanwar says:

    def randomColor():
    return str(hex(randint(0, 16777215)).replace(‘0x’, ”).zfill(6))

    The replace function will remove ‘0x’ from output and the zfill() function will make sure output must be 6 characters long by adding 0 at the start if there is empty place i.e. if your output is like #dcde0 it will convert it like #0dcde0

Leave a Reply

Your email address will not be published. Required fields are marked *