3 ms·
Better yet use enumerate to save looking up the character index: for i,char in enumerate(string): print termcolor.colored(char, colors[i%7])
by absherwin 14y ago
Better yet use enumerate to save looking up the character index:
for i,char in enumerate(string):
print termcolor.colored(char, colors[i%7])
- barakstout 14y agoBoth would work just fine. Good Points.
- andrewcooke 14y agothe first doesn't work correctly for all strings (those with duplicate characters). the second is the right way to do it.
- barakstout 14y agoBoth 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.
- RyanMcGreal 14y agoGood point. I should know better than to dash off a quick code sample on HN without first running a test suite. :)
- hythloday 14y agoYou 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)
- barakstout 14y agoSweet. Thanks.