tuple to string/list

Mark Day mday at apple.com
Thu Aug 21 16:32:21 EDT 2003


In article <538fc8e.0308211141.4bca8a8d at posting.google.com>, WIWA
<wim_wauters at skynet.be> wrote:

> When I write:
> 
> for i in range(len(month)):
>     output="Hits for",month[i], ":" , teller[i]
>     f.write(str(output))
> f.close()
> 
> => this produces a tuple:
> ('Hits for', 'Jan', ':', 0)('Hits for', 'Feb', ':', 2)('Hits for',
> 'Mar', ':', 3)
> 
> => whereas I would like the following output:
> Hits for Jan: 0
> Hits for Feb: 2
> Hits for Mar: 3
> 
> Any easy way of obtaing this output?

Your "output=..." line is building up a tuple.  You could just build up
a string instead.  And don't forget that file.write does not add any
newline, so you have to add it yourself.  Try this:

import os
for i in range(len(month)):
    output="Hits for"+month[i]+":"+str(teller[i])+os.linesep
    f.write(output)
f.close()

You can also use the "print" statement to write to file-like objects. 
And you can use the "%" operator for string formatting:

for i in range(len(month)):
    print >>f, "Hits for %s: %d" % (month[i], teller[i])
f.close()

-Mark




More information about the Python-list mailing list