News for hackers. Stuff that matters.
Re:Playing with Strings and Colors in Python by RyanMcGreal on Friday December 28, 2012 @08:13AM (#4977555)
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])
Re:Playing with Strings and Colors in Python by absherwin on Friday December 28, 2012 @08:22AM (#4977573)
Better yet use enumerate to save looking up the character index:

    for i,char in enumerate(string):
        print termcolor.colored(char, colors[i%7])
Re:Playing with Strings and Colors in Python by hythloday on Friday December 28, 2012 @11:00AM (#4978121)
You can get rid of that unpleasant indexing:

(3.2)

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

    from itertools import cycle, izip
    for colour, character in izip(cycle(colours, string):
      print termcolor.colored(character, colour)
Re:Playing with Strings and Colors in Python by barakstout on Friday December 28, 2012 @11:13AM (#4978176)
Sweet. Thanks.
Re:Playing with Strings and Colors in Python by barakstout on Friday December 28, 2012 @09:03AM (#4977671)
Both would work just fine. Good Points.
Re:Playing with Strings and Colors in Python by andrewcooke on Friday December 28, 2012 @10:30AM (#4978015)
the first doesn't work correctly for all strings (those with duplicate characters). the second is the right way to do it.
Re:Playing with Strings and Colors in Python by RyanMcGreal on Friday December 28, 2012 @11:00AM (#4978125)
Good point. I should know better than to dash off a quick code sample on HN without first running a test suite. :)
Re:Playing with Strings and Colors in Python by barakstout on Friday December 28, 2012 @10:57AM (#4978108)
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.