我正在寻找一种方法来检查字符串是否定义了颜色,因为我的程序依赖于用户输入颜色,并且当他们输入错误的颜色时程序会中断。我怎样才能做到这一点?以下是一些示例:
check_color("blue") > True
check_color("deep sky blue") > True
check_color("test") > False
check_color("#708090") > True
最佳答案
下面是使用 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'
在 matplotlib.colors 模块的源代码中是这样写的:
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.
关于python - 检查字符串是否定义了颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42876366/