TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Playing with Strings and Colors in Python

36 pointsby barakstoutover 12 years ago

5 comments

RyanMcGrealover 12 years ago
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:<p><pre><code> colors = ('grey', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan') for char in string: print termcolor.colored(char, colors[string.index(char)%7])</code></pre>
评论 #4977573 未加载
Osmoseover 12 years ago
I prefer Blessings[1] for terminal colors/positioning/etc (except it's limited to platforms that support curses):<p><pre><code> 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.' </code></pre> [1] <a href="http://pypi.python.org/pypi/blessings/" rel="nofollow">http://pypi.python.org/pypi/blessings/</a>
ses4jover 12 years ago
This is much much <i>much</i> more entry-level than most of the content posted to HN. Maybe a "Beginners: " label would be appropriate...
评论 #4978791 未加载
评论 #4977948 未加载
mmcnickleover 12 years ago
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:<p><pre><code> ATTRIBUTES = dict( list(zip([ 'bold', 'dark', '', 'underline', 'blink', '', 'reverse', 'concealed' ], list(range(1, 9)) )) ) del ATTRIBUTES[''] </code></pre> 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:<p><pre><code> ATTRIBUTES = { 'bold': 1, 'dark': 2, 'underline': 4, 'blink': 5, 'reverse': 7, 'concealed': 8 }</code></pre>
评论 #4978891 未加载
Falling3over 12 years ago
The first paragraph read strangely to me... like bot generated content. Like the sentence:<p>"Python can be written as an algorithm that you can execute."