Checking Hex Color Validity

Description

Valid hex colors are three digit hex colors (e.g., #F00), six digit hex colors (e.g., #FF00FF), or six digit colors with additional transparency (eight digit representation) or None. If the inputs do not match one of these hex representations matplotlib.color.to_hex will be called. This allows to also convert standard colors such as "0", "black", or "magenta" into their corresponding hex representation.

Usage

check_hex_colors(colors)

Arguments

colorsstr, list, numpy.ndarray
str or list of str with colors. See function description for details. In case it is a numpy.ndarray it will be flattened to 1-dimensional if needed.

Return

list: Returns a list (length 1 or more) in case all values provided are valid hex colors or None. Three digit colors will be expanded to six digit colors, all upper case. Else the function will raise a ValueError.

Examples

from colorspace import check_hex_colors
check_hex_colors("#ff003311")
['#FF003311']
check_hex_colors("#ff0033")
['#FF0033']
check_hex_colors("#f03")
['#FF0033']
check_hex_colors(["#f0f", "#00F", "#00FFFF", "#ff003311"])
['#FF00FF', '#0000FF', '#00FFFF', '#FF003311']
check_hex_colors(["#FFF", "0", "black", "blue", "magenta"])
['#FFFFFF', '#000000', '#000000', '#0000FF', '#FF00FF']
check_hex_colors([None, "#ff0033", None])
[None, '#FF0033', None]
from numpy import asarray
check_hex_colors(asarray(["#f0f", "#00F", "#00FFFF", "#ff003311"]))
['#FF00FF', '#0000FF', '#00FFFF', '#FF003311']

Raises

  • ValueError: In case colors is a list but does not only contain strnigs.
  • TypeError: If colors is neither str or list of str.
  • ValueError: If at least one of the colors is an invalid hex color.