Generate Random RGB and Hex Color in Python: A Step Guide – Python Tutorial

By | September 3, 2021

In this tutorial, we will use some examples to introduce how to create rgb color and hex color string in python.

RGB color

RGB color contains red, green and blue color, the value of each color is 0-255. We can generate a random color as follows:

import random

r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)

color = (r, g, b)
print(color)

Run this code, we may get a rgb color: (158, 158, 215)

We also can use numpy to generate a random rgb color, for example:

import numpy as np
rgb = np.random.choice(255, size=3)
color = (rgb[0], rgb[1], rgb[2])
print(color)

Run this code, the rgb color may be: (165, 63, 156)

Hex color string

Hex color string looks like: #ff4455, we can use code below to create:

import random
color="#"+''.join([random.choice('0123456789ABCDEF') for i in range(6)])
print(color)

Run this code, we may get #E4F4EB.

To understand how to use random.choice(), you can read:

Best Practice to Select a Random Element from Python List – Python Tutorial

If you want to conver hex color to rgb, you can read this tutorial:

Best Practice to Python Convert Hex Color to RGB – Python Tutorial

Leave a Reply

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