How to parse CSS colors?

Published at 30, November 2009, author art. Tags: python, snippet

def parse_color(s):
    """ Parses color string in format #ABC or #AABBCC to RGB tuple. """
    l = len(s)
    assert(l in (4,5,7,9))

    if l in (4,5):
        return tuple(int(ch * 2, 16) for ch in s[1:])
    else:
        return tuple(int(ch1 + ch2, 16) for ch1, ch2 in \
                     zip(
                        (ch1 for ch1 in s[1::2]),
                        (ch2 for ch2 in s[2::2])
                        )
                    )

Here is a gist file.

Comments

Subscribe on this post's comments

permalink

30, November 2009, owner of http://iamkrevedko.blogspot... said:

hm.. why not use one iterator for string instead two generator objects ?
eg like this
tuple(int(''.join(a), 16) for a in zip([iter(s[1:])]2))

permalink

01, December 2009, art said:

Thanks, you code much more comprehensive and straight-forward.

permalink

01, December 2009, owner of http://ruslanspivak.com/ said:

Some time ago I had the same task at hand.

Solved using clustering with zip([iter(s)]n).

If you wish to leave comment, please, identify yourself and then come back to this page.