Why can't I join this tuple in Python?

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

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

+41
python list tuples
Nov 29 '09 at 11:41
source share
4 answers

join accepts only 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' 
+82
Nov 29 '09 at 11:43
source share

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

+9
Nov 29 '09 at 11:43
source share

Use the csv module. It will save the subsequent question about how to process elements containing a comma, and then another about processing elements containing a character that you used to quote / exit from a comma.

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

Check this:

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

Output:

 ham,5,1,bird 
+3
Nov 29 '09 at 13:26
source share

Perhaps you better just convert the tuple to a list:

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

+2
Jun 02 '15 at 18:32
source share



All Articles