当我遇到诸如“ä”,“ü”,“ö”等字符时,格式输出错误。
我从excel-sheet-column中读取名称,这些名称有时带有Unicode字符串,我将其编码为UTF-8。我的简化代码:
import xlrd
name1 = (xl_sheet.cell_value(row,5)).encode('utf8') # use this because this cell can have strings with chars like "ö"
name2 = (xl_sheet.cell_value(row,7)).encode('utf8')
print('{:<15} {:<15}'.format(name1,name2)),
当我不使用.encode时,出现此错误:
'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)
我发现了一个类似的帖子:Python String format width wrong when characters like é or ö in the string,但是我不知道该如何实现!
我的输出表是这样的:
oabcd oabcd
öabcd oabcd
oabcd oabcd
当f.e. char'ö'在变量中,则输出不正确。
Excel文件具有CP-1252“ Windows Unicode”编码。
xlrd.open_workbook(filename).encoding的输出是:utf_16_le。
最佳答案
这很简单:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
做到这一点。不需要主代码中的.encode('utf8')。