[Tutor] Re: Why is this write defined as a tuple, instead of picking list?

Andrei project5 at redrival.net
Fri Apr 16 14:22:37 EDT 2004


Adam wrote on Friday 16 April 2004 12:16:

> I'm using this function to cycle through a list and add some
> formatting to it to prepare it for saving:
<snip>
>     for x in article_items:
>         write = "<h3>", article_items[0], "</h3>"
>         print "write is type: ", type(write)
<snip>
> At the time article_items is passed it is a list - however,
> when I try to do the formatting with write =, write is
> declared as a tuple - why is this, and how can I force it to
> be a string (I believe I need a string for the file saving
> function?)

The relevant line looks like this:

   write = "a", "b", "c'

This happens to be syntax for tuples, meaning that write becomes a tuple. If
you want to concatenate strings, you should use "+":

   write = "a" + "b" + "c"

It is generally not recommended to use this, because it's slow. It's better
to have a list of substrings like this:

  write = ["a", "b", "c"]

and then use the string method join() to convert that list into a string
when you really need it to be a string (e.g. before writing to a file):

  strwrite = "".join(write)

Have a good look at this syntax, many (or even most) people find it
counter-intuitive at first. "" is the separator char that will be inserted
between the string parts in the list. In this case it's an empty string,
but you could also use "\n" (newline) for example to make each of the
substrings appear on a new line in the concatenated string.

In this particular (partial) case, I'd even recommend string formatting:

  write = "<h3>%s</h3>" % article_items[0]

But if you plan to add more content to the HTML page, the solution with a
list which is joined at a later point in time is the best one.


Btw, I don't understand this logic:

>     for x in article_items:
>         write = "<h3>", article_items[0], "</h3>"

Why are you writing the same header for every item in the list?

-- 
Yours,

Andrei

=====
Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.




More information about the Tutor mailing list