Create Random Hex Color Code Using Python
Last Updated :
25 Aug, 2023
A Hexadecimal color code represents a color code in hexadecimal form. Color codes are the defacto method of representing a color. It helps accurately represent the color, regardless of the display calibration. This article will teach you how to create random hexadecimal color codes in Python.
RGB Color Code
An RGB color code is a tuple containing 3 numbers representing Red, Green, and Blue color values, respectively. Ex. The color code tuple for a 24-bit color system (channel_intensity < 256) would be:
Syntax: (X, Y, Z)
Where,
- X => Red channel intensity
- Y => Green channel intensity
- Z => Blue channel intensity
And the intensity of all channels should be less than 256 (for an 8-bit per channel system).
Hence for pure red color, the color code would be
(255, 0, 0)
Where
- Red = 255
- Green = 0
- Blue = 0
Similarly, over 16 million colors could be uniquely represented. Throughout the article, the 8-bit per channel color space would be considered.
Creating Random Hex Color Codes in Python
Generating a Color code in decimal and then converting it into a Hexadecimal base is the method for achieving the desired result. The process is trivial and could be accomplished easily by using a random value generator such as randint.
Using Randint and format specifiers
randint() is a function inside the random module, allowing the compiler to produce pseudo-random values in a specific range. The syntax of the function is as follows:
Syntax: randint(a, b)
Return random integer in range [a, b], including both end points.
Where a and b are two integers.
The above function will generate a random value in the RGB color space if the range is from 0 to 224. The following example demonstrates the effect produced:
Python3
import random
color = random.randrange( 0 , 2 * * 24 )
hex_color = hex (color)
print (hex_color)
|
Output:
0xd9e906
Explanation:
Firstly a random number is generated in between the range 0 to 224. This is the range for a 24-bit RGB color code. The output of the function is in decimal (base-10) hence it needs to be converted to hexadecimal. For that, the random number is passed to the hex function, which produces the hexadecimal equivalent of the argument to the function. Therefore, the function returns the hexadecimal representation of the number passed to it, and in the end, the hex code is displayed.
Notes: The range 0 to 224 is only for a 24-bit RGB color code. For 8-bit grayscale, the range will be 0 to 28. Hence, the value of the endpoint depends upon the range offered by the color space.
Requirement for usable hex codes
The hex color codes that are used to represent the color are generally in the following format:
#(Six_digit_color_code)
Where the Six_digit_color_code is any 24-bit color code. Hence, the color codes have a pound sign prepended to them. Ex. The color code for a black image would be:
#000000
Therefore, to make the program produce hex color codes of the aforementioned structure, the code will be:
Python3
import random
color = random.randrange( 0 , 2 * * 24 )
hex_color = hex (color)
std_color = "#" + hex_color[ 2 :]
print (std_color)
|
Output:
#d9e906
Explanation:
The code is a modified version of the previous code. The modifications were string slicing to remove the first two characters of the string (“0x”) and to prepend the pound sign (“#”) at the start of the string.
Using choice function
The secrets module is a part of the standard Python distribution. The module generates cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets. The module contains two functions, namely choice and token_hex
The following code displays how to produce hexadecimal color code using the choice function:
Python3
import secrets
s = ""
x = 0
while x < 6 :
s + = secrets.choice( "0123456789ABCDEF" )
x + = 1
print (s)
|
Output:
61A33B
Explanation:
Firstly an empty string is initialized that will contain the hexadecimal string. Then a variable is defined that would be used to iterate over a loop. Then a loop is run for 6 iterations (6 characters in a hexadecimal color code) and will produce a random hexadecimal character in each iteration and append that to the empty string. In the end, the string is displayed.
Using token_hex function:
The following code displays how to produce hexadecimal color code using the token_hex function:
Python3
import secrets
s = secrets.token_hex( 3 )
print (s)
|
Output:
c62e02
Explanation:
This code is the shortest of all the ones described in the article. A call to the token_hex function is made, and the hexadecimal string length is passed as an argument. The reason for passing 3 instead of 6 is that the function takes in argument bytes, where each byte is converted to 2 hexadecimal digits. Hence only 3 needed to be sent as an argument to produce a 6-digit hex string.
Using the randomcolor module to generate a random hex color code:
The randomcolor library is a Python library that generates random, aesthetically pleasing colors using the HSV (Hue, Saturation, Value) color space. It can be used to generate a single random color or a list of random colors.
To use the randomcolor library, you will need to install it first using pip. Open a terminal and enter the following command:
pip install randomcolor
Once the library is installed, you can import it in your Python code and use it to generate a random color. Here is an example of how to use the randomcolor library to generate a single random color:
Python3
import randomcolor
color = randomcolor.RandomColor().generate()
print (color)
|
You can also use the randomcolor library to generate a random color. To do this, you can use the generate method of the RandomColor class.
Output:
['#451099']
Using Webcolors
Requirements:
Webcolors Module- The “webcolors” module in Python simplifies colour management by converting color names and codes. It supports CSS color names and is useful for web development, graphics, and data visualization. The module is flexible and supports the CSS color names standard.
To install the webcolors package run the following code in the Terminal Window:
pip install webcolors
Procedure
- To translate colour names into hex colour codes, the code makes use of the name_to_hex function from the webcolors module.
- To manage any possible errors, the color_name_to_code function includes the name_to_hex function call in a try-except block.
- The function gives back the colour code if the conversion was successful. It returns None in all other cases.
- The code prompts the user to provide a colour name and stores it in the colorname variable.
- The user’s input is passed to the color_name_to_code function, which converts the colour name to a colour code.
Code:
Python3
from webcolors import name_to_hex
def color_name_to_code(color_name):
try :
color_code = name_to_hex(color_name)
return color_code
except ValueError:
return None
colorname = input ( "Enter color name : " )
result_code = color_name_to_code(colorname)
print (result_code)
|
Output:
Enter color name: Orange
#ffa500
Similar Reads
Create Random RGB Color Code using Python
Color codes are the defacto method of representing a color. It helps accurately represent the color, regardless of the display calibration. This article will teach you how to create random RGB color code using Python. RGB Color Code An RGB color code is a tuple containing 3 numbers representing Red,
3 min read
How to add colour to Excel cells using Python
To add color to Excel cells we will be using the Openpyxl Python Library. The Openpyxl module allows us to read and modify Excel files using Python. Approach 1: Using the Openpyxl module, even small tasks can be done very efficiently and easily in excel. Input File: Only declare the excel name with
2 min read
Generate QR Code using qrcode in Python
A Quick Response Code or a QR Code is a two-dimensional bar code used for its fast readability and comparatively large storage capacity. It consists of black squares arranged in a square grid on a white background. Python has a library "qrcode" for generating QR code images. It can be installed usin
2 min read
Color game using Tkinter in Python
TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to
4 min read
Convert hex string to float in Python
Converting a hex string to a float in Python involves a few steps since Python does not have a direct method to convert a hexadecimal string representing a float directly to a float. Typically, a hexadecimal string is first converted to its binary representation, and then this binary representation
3 min read
Design Random Color Generator using HTML CSS and JavaScript
A Random Color Generator app is used to create random colors with a simple button click, displaying both HEX and RGB codes that users can copy. It's built using HTML, CSS, and JavaScript, making it a handy tool for designers or developers who need quick color ideas. The app can also include a Dark M
3 min read
Python | Generate QR Code using pyqrcode module
Let's see how to generate QR code in Python using pyqrcode module. pyqrcode module is a QR code generator. The module automates most of the building process for creating QR codes. This module attempts to follow the QR code standard as closely as possible. The terminology and the encodings used in py
2 min read
Python code formatting using Black
Writing well-formatted code is very important, small programs are easy to understand but as programs get complex they get harder and harder to understand. At some point, you canât even understand the code written by you. To avoid this, it is needed to write code in a readable format. Here Black come
3 min read
How to use Color Palettes in Python-Bokeh?
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity. Bokeh provides us with multiple color palettes in the bokeh
7 min read
Convert Hex to String in Python
Hexadecimal (base-16) is a compact way of representing binary data using digits 0-9 and letters A-F. It's commonly used in encoding, networking, cryptography and low-level programming. In Python, converting hex to string is straightforward and useful for processing encoded data. Using List Comprehen
2 min read