[Tutor] ok, I want to read a dir.
Fri, 28 Dec 2001 09:57:23 -0800
> Kirk Bailey <email@example.com> wrote:
> print "<a href= \"" + webpath + "cgi-bin/commander.py?list=" + x
> + "\">" + x + "</a> ", descriptor(x) +'<P>'
> #which means:
> # print 'a
Do yourself (and us! ;) ) a favor, and learn to use string formatting. Adding strings
together like you do above, is both slow and error-prone. It hurts my head just looking
at that line and trying to figure out which parts are string and which parts are
variable and which quotation marks go with which chunks and..... :)
If you use string formatting instead, that line becomes:
print '<a href="%scgi=bin/commander.py?list=%s">%s</a>%s<p>' %
(webpath, x, x, descriptor(x))
Every place in the main string that you see a %s, Python will replace that with the
string value of the corresponding variable from the final tuple. This has several
advantages over the multiple-concatenation that you were doing. For one, it's a *lot*
cleaner and easier to read. And it's much faster and more efficient--it creates a
single new string object, and all the substitution is done in C code in the
interpreter. Your example creates almost a dozen new string objects, only to throw them
away almost immediately, not to mention setup and type checks and such that have to be
done with each and every addition...
If you are doing *any* work with text or strings, then the string-formatting operator is
your friend. Learn to know it well, and it will help you immensely. :)