how do i get RGB from HEX?
Bengt Richter
bokr at oz.net
Sat Mar 23 15:59:03 EST 2002
On Fri, 22 Mar 2002 16:49:24 +0000, Robin Becker <robin at jessikat.fsnet.co.uk> wrote:
>In article <a7flgu$cpg$1 at newsg1.svr.pol.co.uk>, G. Willoughby
><sab at NOSPAM.freeuk.com> writes
>>Hi,
>> i have been trying to do this for to long now, i know there is an easy
>>way, please somebody put me out of my misery! i need to get the RGB value of
>>a HEX number (eg, #DCDCDC). can anyone help?
>>
>>thanks,
>>
>>G. Willoughby
>>
>>
>split into pairs after stripping the #
>
>>>> def rgb(h):
>... n = eval('0x'+h[1:])
>... return (n>>16)&0xff, (n>>8)&0xff, n&0xff
>...
>>>> rgb('#DCDC0a')
,-^^
|
???
|
vvv
>(220, 220, 220)
>>>> rgb('#DCDC0a')
>(220, 220, 10)
>>>>
>
>I'm sure there's probably some better way, but the above works.
A little better ;-) Avoiding eval when possible, e.g.,
>>> def rgb(h):
... n = int(h[1:],16)
... return (n>>16)&0xff, (n>>8)&0xff, n&0xff
...
>>> rgb('#DCDCDC')
(220, 220, 220)
>>> rgb('#DCDC0a')
(220, 220, 10)
>>> rgb('#0a')
(0, 0, 10)
Regards,
Bengt Richter
More information about the Python-list
mailing list