我得到一个错误的格式输出,当我有像“ä”,“ü”“ö”等字符。 我从excel表栏读取名称,有时会有Unicode字符串,我编码为UTF-8。我的简化代码:格式: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。
这只是一个简单的例子。我在程序的早些时候有一个变量。当我尝试你的建议时,我得到了错误:UnicodeDecodeError:'ascii'编解码器无法解码位置1中的字节0xc3:序号不在范围(128)中。因此我使用了.encode()。 – user3265764
那么你以后为用户保存变量......实质上,你链接的帖子建议在unicode中做所有事情,并且不要打扰ascii和编码的东西。这应该解决你在'print'语句中遇到的空间问题。你认为你可以用违规代码更新你的问题吗? – Zizouz212