top | item 4977309

Playing with Strings and Colors in Python

36 points| barakstout | 13 years ago |thelivingpearl.com

15 comments

order
[+] RyanMcGreal|13 years ago|reply
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])
[+] absherwin|13 years ago|reply
Better yet use enumerate to save looking up the character index:

    for i,char in enumerate(string):
        print termcolor.colored(char, colors[i%7])
[+] Osmose|13 years ago|reply
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/
[+] ses4j|13 years ago|reply
This is much much much more entry-level than most of the content posted to HN. Maybe a "Beginners: " label would be appropriate...
[+] jevinskie|13 years ago|reply
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!
[+] barakstout|13 years ago|reply
Maybe it will. Noted for future reference.
[+] mmcnickle|13 years ago|reply
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(zip([
            'bold',
            'dark',
            '',
            'underline',
            'blink',
            '',
            'reverse',
            'concealed'
            ],
            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:

    ATTRIBUTES = {
        'bold': 1,
        'dark': 2,
        'underline': 4,
        'blink': 5,
        'reverse': 7,
        'concealed': 8
    }
[+] viraptor|13 years ago|reply
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))
[+] Falling3|13 years ago|reply
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."