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

Requirement:

  • random library

Code:

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)

Output:

A Random Hex Color Code is : #d68637

Process:




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

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)

Output:

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:


Leave a Reply

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