Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string defines a color

Tags:

python

colors

I'm looking for a way to check if a string defines a color since my program relies on users inputting colors and it breaks when they enter a wrong color. How can I do this? Here are some examples:

check_color("blue") > True
check_color("deep sky blue") > True
check_color("test") > False
check_color("#708090") > True
like image 758
nomis6432 Avatar asked Mar 18 '17 15:03

nomis6432


2 Answers

Here is the way to check if the string defines a color using matplotlib:

>>> from matplotlib.colors import is_color_like
>>>
>>> is_color_like('red')
True
>>> is_color_like('re')
False
>>> is_color_like(0.5)
False
>>> is_color_like('0.5')
True
>>> is_color_like(None)
False
>>>
>>> matplotlib.colors.__file__
'/usr/lib/python2.7/site-packages/matplotlib/colors.py'

In the source code of the matplotlib.colors module it's written:

The module also provides functions for checking whether an object can be interpreted as a color (:func:is_color_like), for converting such an object to an RGBA tuple (:func:to_rgba) or to an HTML-like hex string in the #rrggbb format (:func:to_hex), and a sequence of colors to an (n, 4) RGBA array (:func:to_rgba_array). Caching is used for efficiency.

like image 192
JenyaKh Avatar answered Oct 17 '22 15:10

JenyaKh


One possible way might be is to use colour package. If you do not have it install use command pip install colour. Then, you can use following:

from colour import Color

def check_color(color):
    try:
        # Converting 'deep sky blue' to 'deepskyblue'
        color = color.replace(" ", "")
        Color(color)
        # if everything goes fine then return True
        return True
    except ValueError: # The color code was not found
        return False

check_color("blue") 
check_color("deep sky blue")
check_color("test") 
check_color("#708090")
like image 42
student Avatar answered Oct 17 '22 15:10

student