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 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.
Re:Playing with Strings and Colors in Python
by Osmose on Friday December 28, 2012 @12:39PM
(#4978543)
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.'
Re:Playing with Strings and Colors in Python
by jevinskie on Friday December 28, 2012 @01:27PM
(#4978791)
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!
Re:Playing with Strings and Colors in Python
by mmcnickle on Friday December 28, 2012 @01:13PM
(#4978725)
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:
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:
(3.2)
(2.7)EDIT: The only issue is that if the string has a repeated letter it will be the same color.
"Python can be written as an algorithm that you can execute."