Why can't I join this tuple in Python?

PythonTuples

Python Problem Overview


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

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

Python Solutions


Solution 1 - Python

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'

Solution 2 - Python

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

Solution 3 - Python

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

liste = list(e)
','.join(liste)```

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - PythonNick Craig-WoodView Answer on Stackoverflow
Solution 2 - PythondjcView Answer on Stackoverflow
Solution 3 - Pythonuser4805123View Answer on Stackoverflow
Solution 4 - PythonJohn MachinView Answer on Stackoverflow