Why can't I join this tuple in Python?

喜欢而已 提交于 2019-12-03 04:04:53

问题


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

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


回答1:


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'



回答2:


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




回答3:


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

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




回答4:


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


来源:https://stackoverflow.com/questions/1815316/why-cant-i-join-this-tuple-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!