TIMEX
TIMEX

Reputation: 272134

Why can't I join this tuple in Python?

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

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

Upvotes: 64

Views: 78443

Answers (4)

djc
djc

Reputation: 11731

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

Upvotes: 12

user4805123
user4805123

Reputation:

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

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

Upvotes: 3

John Machin
John Machin

Reputation: 82992

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

Upvotes: 3

Nick Craig-Wood
Nick Craig-Wood

Reputation: 54107

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'

Upvotes: 138

Related Questions