tags:

views:

331

answers:

3
e = ('ham', 5, 1, 'bird')
logfile.write(','.join(e))

I have to join it so that I can write it into a text file.

+3  A: 

join() only works with strings, not with integers. Use ','.join(str(i) for i in e).

djc
+14  A: 

join only takes lists of strings, so convert them first

>>> e = ('ham', 5, 1, 'bird')
>>> ','.join(map(str,e))
'ham,5,1,bird'

Or maybe more pythonic

>>> ','.join(str(i) for i in e)
'ham,5,1,bird'
Nick Craig-Wood
using str() instead of repr() can cause LOSS OF INFORMATION.
John Machin
It depends on what your purpose is, but `str()` is generally what you want to show something to the user (ie in a logfile which was what the OP wanted).
Nick Craig-Wood
Indeed. str (__str__ or better, __unicode__) is for humans. And the question states a logfile, which is for humans. So in this case I think str() is better than __repr__.
extraneon
Users don't read log files; if inadequately supervised, they ignore them until they run out of disk space then they delete them. Programmers have to read logfiles when investigating problems. Having blurred evidence is at best a major annoyance.
John Machin
logfile is just the object name. (out of conveinence). Actually, I do want humans to read them :)
TIMEX
+3  A: 

Use the csv module. It will save a follow-up question about how to handle items containing a comma, followed by another about handling items containing the character that you used to quote/escape the commas.

import csv
e = ('ham', 5, 1, 'bird')
with open('out.csv', 'wb') as f:
    csv.writer(f).writerow(e)

Check it:

print open('out.csv').read()

Output:

ham,5,1,bird
John Machin