Generating Random Hex Colors in Python

Introduction

Let's say you're building a visualization tool and need to generate a few colors - how would you do that? Or maybe you have a base color and need to generate one that's similar. These are just a few use-cases in which you'd need to figure out how to generate random hexadecimal colors.

In this Byte, we'll walk you through a few ways to create these colors in Python.

Generating Random Hex Colors

Luckily the task is pretty straightforward, thanks to the built-in random module. Each color in the hexadecimal format is represented by a six-digit combination of numbers and letters (from A to F), where each pair of digits represents the intensity of red, green, and blue colors, respectively.

Here's a simple way to generate random hexadecimal colors:

import random

def generate_random_color():
    return '#{:06x}'.format(random.randint(0, 0xFFFFFF))

print(generate_random_color())

When you run this code, you'll get a random color each time. The {:06x} is a format specification for six hexadecimal digits, prefixed with a '#'.

Using random.choice() in Older Python Versions

If you're using an older version of Python, you can still generate random hexadecimal strings with the random.choice() function. Here's how:

import random

def generate_random_color():
    return '#' + ''.join([random.choice('0123456789ABCDEF') for _ in range(6)])

print(generate_random_color())

This code generates a random color by choosing a random character from the string '0123456789ABCDEF' six times.

Random Hex Colors with Formatted String Literals

Python 3.6 introduced a new way of handling string formatting - Formatted String Literals, or f-strings. You can use these to generate random hex colors as well:

Get free courses, guided projects, and more

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

import random

def generate_random_color():
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    return f'#{r:02x}{g:02x}{b:02x}'

print(generate_random_color())

This code generates random values for red, green, and blue, and then formats them as two-digit hexadecimal numbers.

Sure, I'll help you expand on your article by adding an introduction, a section on creating random colors within a certain range restriction, and a conclusion. I'll try to maintain a conversational tone throughout.

Generating Random Hex Colors within a Range

Sometimes, you might want to restrict the range of your colors to get a specific look or theme. Let's say you want to create only shades of blue. You can do that by keeping the red and green channels at zero (or some other low value) and only generating random values for the blue channel. Here's one way to do that:

import random

def generate_random_blue():
    return f'#0000{random.randint(0, 255):02x}'

print(generate_random_blue())

You can even specify ranges for red, green, and blue to get a color within a specific spectrum:

def generate_random_color_within_range(r_min, r_max, g_min, g_max, b_min, b_max):
    r = random.randint(r_min, r_max)
    g = random.randint(g_min, g_max)
    b = random.randint(b_min, b_max)
    return f'#{r:02x}{g:02x}{b:02x}'

print(generate_random_color_within_range(100, 150, 50, 100, 200, 255))

With this, you'll get a random color within the defined RGB ranges, allowing you to control the overall hue, saturation, and brightness.

Conclusion

Whether you're looking for a bit of randomness or a more controlled shade, generating random hex colors in Python is pretty easy. From classic techniques to the newer f-strings, Python many ways to achieve this.

Last Updated: August 17th, 2023
Was this helpful?

Ā© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms