Skip to content

Easy Colors

py_simple.easy_colors

Beginner-friendly helpers for hex and RGB color handling.

hex_to_rgb(hex_code)

Converts a hex color code string to an (R, G, B) integer tuple.

Supports 3-digit and 6-digit hex color codes with or without '#'.

Parameters:

Name Type Description Default
hex_code str

Hex color string to convert (e.g., "#FFFFFF" or "fff").

required

Returns:

Type Description
tuple[int, int, int]

tuple[int, int, int]: RGB values as (r, g, b) integers in range 0-255.

Raises:

Type Description
ValueError

If hex_code is not a valid hex color.

Example
from py_simple import hex_to_rgb

hex_to_rgb("#FFFFFF")  # -> (255, 255, 255)
hex_to_rgb("00ff00")  # -> (0, 255, 0)
hex_code = "#FFFFFF".lstrip("#")
if len(hex_code) == 3:
    hex_code = "".join(c * 2 for c in hex_code)
r, g, b = tuple(int(hex_code[i : i + 2], 16) for i in (0, 2, 4))

is_valid_hex(hex_code)

Checks whether a string is a valid hex color code.

Supports 3-digit and 6-digit hex color formats, with or without a leading '#' prefix.

Parameters:

Name Type Description Default
hex_code str

Color string to check.

required

Returns:

Name Type Description
bool bool

True if hex_code is a valid hex color, False otherwise.

Example
from py_simple import is_valid_hex

is_valid_hex("#FFFFFF")  # -> True
is_valid_hex("fff")  # -> True
is_valid_hex("invalid")  # -> False
import re

hex_code = "#FFFFFF"
cleaned = hex_code.lstrip("#")
is_valid = len(cleaned) in (3, 6) and all(
    c in "0123456789abcdefABCDEF" for c in cleaned
)

rgb_to_hex(r, g, b)

Converts (R, G, B) color values to a hex color string.

Parameters:

Name Type Description Default
r int

Red channel value (0 to 255).

required
g int

Green channel value (0 to 255).

required
b int

Blue channel value (0 to 255).

required

Returns:

Name Type Description
str str

Uppercase hex color string (e.g., "#FFFFFF").

Raises:

Type Description
ValueError

If any channel is outside the 0-255 range.

TypeError

If any channel is not an integer.

Example
from py_simple import rgb_to_hex

rgb_to_hex(255, 255, 255)  # -> "#FFFFFF"
rgb_to_hex(0, 128, 64)  # -> "#008040"
r, g, b = 255, 255, 255
hex_code = f"#{r:02X}{g:02X}{b:02X}"