我有一个数组如下:
row = [u'Arun DC', 4.0, 34.0, 76.0, 223.52941176470588, u'yes', 0.0, '', '', '', '', u'yes', '', u'yes', u'yes', u'yes', u'no', u'\xa37.50 - \xa310 not clear what this is for', u'\xa37.50 - \xa310 not clear what this is for', '', u'\xa37.50 - \xa310 not clear what this is for', u'\xa37.50 - \xa310 not clear what this is for', '', '', '', '', u'no water on sites', '', u'1st years rent free', '']
我想将其写入CSV文件,但是我收到以下错误:
writer.writerow(row)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 0: ordinal not in range(128)
所以我先尝试对它进行编码,但这给了我一个错误,因为我无法对浮动项进行编码:
writer.writerow([i.encode('latin-1') for i in row])
AttributeError: 'int' object has no attribute 'encode'
有什么想法以一种巧妙的方式来解决这个问题吗?
答案 0 :(得分:8)
[x.encode('latin-1') if isinstance(x, unicode) else x
for x in row]
答案 1 :(得分:1)
[i.encode('latin-1') if isinstance(i, unicode) else i for i in row]
答案 2 :(得分:1)
[('%s'%a).encode('latin-1') for a in row]
返回字符串列表。您可以使用它来写出CSV。