Hacker News new | comments | show | ask | jobs | submit login
Playing with Strings and Colors in Python (thelivingpearl.com)
36 points by barakstout 1757 days ago | hide | past | web | 15 comments | favorite

Python is a great language for iterating over collections - lists, tuples, dicts, sets, etc. - and all those elifs don't look very Pythonic to me. Let's clean it up a little:

    colors = ('grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan')
    for char in string:
        print termcolor.colored(char, colors[string.index(char)%7])

Better yet use enumerate to save looking up the character index:

    for i,char in enumerate(string):
        print termcolor.colored(char, colors[i%7])

You can get rid of that unpleasant indexing:


    from itertools import cycle
    for colour, character in zip(cycle(colours), string):
      print(termcolor.colored(character, colour))

    from itertools import cycle, izip
    for colour, character in izip(cycle(colours, string):
      print termcolor.colored(character, colour)

Sweet. Thanks.

Both would work just fine. Good Points.

the first doesn't work correctly for all strings (those with duplicate characters). the second is the right way to do it.

Good point. I should know better than to dash off a quick code sample on HN without first running a test suite. :)

Both versions will work just fine. And number mod 7 will give an index of 0 to 6, which covers any color index from the colors tuple. Also, I tested it out just in case.

EDIT: The only issue is that if the string has a repeated letter it will be the same color.

I prefer Blessings[1] for terminal colors/positioning/etc (except it's limited to platforms that support curses):

    from blessings import Terminal
    t = Terminal()
    print t.bold, 'Hi there!', t.normal
    print t.bold_red_on_bright_green('It hurts my eyes!')
    with t.location(0, t.height - 1):
        print 'This is at the bottom.'
[1] http://pypi.python.org/pypi/blessings/

This is much much much more entry-level than most of the content posted to HN. Maybe a "Beginners: " label would be appropriate...

I would hardly consider myself a python beginner and I was delighted to read this article. I now know how to add some useful "syntax highlighting" to my personal CLI utilities!

Maybe it will. Noted for future reference.

I'm not sure if you were looking for any criticism. I found the way that the way the ATTRIBUTES, HIGHLIGHTS and COLORS dicts are defined to be unnecessarily difficult to read:

    ATTRIBUTES = dict(
            list(range(1, 9))
    del ATTRIBUTES['']
It may feel like you are being more DRY by not typing the numerical values out. But this is data and it's perfectly fine to explicitly define them. The result is straightforward, more compact and easier to read as a result:

        'bold': 1,
        'dark': 2,
        'underline': 4,
        'blink': 5,
        'reverse': 7,
        'concealed': 8

Or even this if you don't want explicit numbers, but don't want that many zip/list/dict/range/etc.:

    attrs = ['bold', 'dark', '', 'underline', 'blink', '', 'reverse', 'concealed']
    ATTRIBUTES = dict((k,v) for v,k in enumerate(attrs, 1) if k)
    # or
    ATTRIBUTES = dict(zip(itertools.count(1), attrs))

The first paragraph read strangely to me... like bot generated content. Like the sentence:

"Python can be written as an algorithm that you can execute."

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact