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

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

sohnryang
  • 725
  • 2
  • 13
  • 27
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
  • 10
    BTW, did you know you can write your first line without the parentheses? It's nice to do away with what is essentially noise. – djc Nov 29 '09 at 11:44

4 Answers4

136

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
  • 52,955
  • 12
  • 126
  • 132
  • 4
    using str() instead of repr() can cause LOSS OF INFORMATION. – John Machin Nov 29 '09 at 13:32
  • 1
    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 Nov 29 '09 at 14:07
  • 1
    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 Nov 29 '09 at 16:50
  • 1
    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 Nov 29 '09 at 22:30
  • logfile is just the object name. (out of conveinence). Actually, I do want humans to read them :) – TIMEX Nov 29 '09 at 23:32
12

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

HamZa
  • 14,671
  • 11
  • 54
  • 75
djc
  • 11,603
  • 5
  • 41
  • 54
4

You might be better off simply converting the tuple to a list first:

e = ('ham', 5, 1, 'bird') liste = list(e) ','.join(liste)

3

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
jfs
  • 399,953
  • 195
  • 994
  • 1,670
John Machin
  • 81,303
  • 11
  • 141
  • 189