检查字符串是否定义了颜色 [英] Check if a string defines a color
问题描述
我正在寻找一种检查字符串是否定义颜色的方法,因为我的程序依赖于用户输入颜色,并且当用户输入错误的颜色时它会中断.我怎样才能做到这一点?以下是一些示例:
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
推荐答案
以下是使用matplotlib检查字符串是否定义颜色的方法:
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'
在matplotlib.colors模块的源代码中编写为:
In the source code of the matplotlib.colors module it's written:
该模块还提供用于检查对象是否可以被识别的功能.解释为一种颜色(:func:
is_color_like
),用于转换此类对象到RGBA元组(:func:to_rgba
)或到HTML中类似HTML的十六进制字符串#rrggbb
格式(:func:to_hex
),以及(n,4)
的颜色序列RGBA阵列(:func:to_rgba_array
).缓存用于提高效率.
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.
这篇关于检查字符串是否定义了颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!