webcolors: HTML/CSS Color Formats

25.10.0 · active · verified Sat Mar 28

webcolors is a Python library designed for working with and converting between various HTML/CSS color formats. It provides functions to normalize and convert between specification-defined color names, six-digit hexadecimal, three-digit hexadecimal, and integer and percentage rgb() triplets, focusing exclusively on the RGB color space. The current version is 25.10.0, and the project maintains an active release cadence with updates typically several times a year.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates common conversions between hexadecimal color codes, color names (using CSS3/SVG specification), and integer RGB triplets. It includes error handling for cases where a direct color name match might not exist.

import webcolors

# Convert a hex code to a color name (using CSS3/SVG names)
hex_color = '#F08080' # Light Coral
try:
    name = webcolors.hex_to_name(hex_color, spec='css3')
    print(f"Hex '{hex_color}' is named '{name}'.")
except ValueError as e:
    print(f"Could not find name for '{hex_color}': {e}")

# Convert a color name to a hex triplet
color_name = 'rebeccapurple'
try:
    hex_val = webcolors.name_to_hex(color_name)
    print(f"Color name '{color_name}' corresponds to hex '{hex_val}'.")
except ValueError as e:
    print(f"Could not find hex for '{color_name}': {e}")

# Convert an integer RGB triplet to a hex code
rgb_triplet = (255, 165, 0) # Orange
hex_from_rgb = webcolors.rgb_to_hex(rgb_triplet)
print(f"RGB {rgb_triplet} converts to hex '{hex_from_rgb}'.")

view raw JSON →