webcolors: HTML/CSS Color Formats
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
- breaking Python 2.x support was dropped, and string arguments on Python 3 became strictly `str` (Unicode), not `bytes`. Attempting to use `bytes` will raise an exception.
- gotcha webcolors consistently returns 'gray' over 'grey' for the hexadecimal value #808080 (rgb(128, 128, 128), or rgb(50%, 50%, 50%)) when querying color names.
- gotcha The library exclusively handles RGB color values and does not support alpha channels (transparency), such as `rgba()` or `#rrggbbaa` formats. Conversion to/from HSL is also not directly supported by `webcolors` itself.
- gotcha Conversions involving percentage `rgb()` triplets (`rgb_to_rgb_percent()` and `rgb_percent_to_rgb()`) may exhibit floating-point imprecision for certain values due to the nature of IEEE floating-point arithmetic. Common values (0, 16, 32, 64, 128, 255) are special-cased for precision, but others are rounded to two decimal places.
Install
-
pip install webcolors
Imports
- webcolors
import webcolors
Quickstart
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}'.")