Python给出了;序号不在范围内“;来自_ustr__;但不来自打印的错误
我有一个从JSON文件中读取一些数据的对象。一些JSON数据是带有拉丁1字符的字符串,例如:Python给出了;序号不在范围内“;来自_ustr__;但不来自打印的错误,python,unicode,encoding,Python,Unicode,Encoding,我有一个从JSON文件中读取一些数据的对象。一些JSON数据是带有拉丁1字符的字符串,例如: "name" : "frisée" 我将该对象字符串化为一个表,其中包含从JSON对象读取的一些字符串。如果我这样写: def __str__(self): # Never mind the details, what matters is that I use __str__ ts = [p + (count,) for p, count in self.counts.items()]
"name" : "frisée"
我将该对象字符串化为一个表,其中包含从JSON对象读取的一些字符串。如果我这样写:
def __str__(self): # Never mind the details, what matters is that I use __str__
ts = [p + (count,) for p, count in self.counts.items()]
ts.sort(key=lambda x:(x[2], x[0], x[1]))
return "\n".join(["%s\t%s\t%s" % (t[0], t[1], t[2]) for t in ts])
def to_string(self):
ts = [p + (count,) for p, count in self.counts.items()]
ts.sort(key=lambda x:(x[2], x[0], x[1]))
return "\n".join(["%s\t%s\t%s" % (t[0], t[1], t[2]) for t in ts])
然后尝试运行print MyObject()
I得到错误:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 9112: ordinal not in range(128)
但是,如果我这样写:
def __str__(self): # Never mind the details, what matters is that I use __str__
ts = [p + (count,) for p, count in self.counts.items()]
ts.sort(key=lambda x:(x[2], x[0], x[1]))
return "\n".join(["%s\t%s\t%s" % (t[0], t[1], t[2]) for t in ts])
def to_string(self):
ts = [p + (count,) for p, count in self.counts.items()]
ts.sort(key=lambda x:(x[2], x[0], x[1]))
return "\n".join(["%s\t%s\t%s" % (t[0], t[1], t[2]) for t in ts])
然后运行print MyObject()。到\u string()
一切正常。“é”字符打印正确
为什么\uuuu str\uuuu
的行为与到字符串的行为不同?如何使\uuu str\uuu
版本正确打印
我尝试了各种迭代的encode
,但都没有成功。您的\uuu str\uuu
正在返回一个unicode
类型值;JSON字符串始终是Unicode。但是,。如果不这样做,Python将为您调用结果上的str()
,这意味着它将使用默认的ASCII编解码器对任何Unicode进行隐式编码
对结果进行显式编码:
def __str__(self):
ts = [p + (count,) for p, count in self.counts.items()]
ts.sort(key=lambda x:(x[2], x[0], x[1]))
return u'\n'.join([u'\t'.join(t[:2]) for t in ts]).encode('utf8')
或者改用一个字母。但是,print
不会调用此命令;您必须使用打印unicode(MyObject())
明确地执行此操作
print
知道如何正确编码unicode
字符串,前提是您的终端配置正确。它将使用sys.stdout.encoding
对Unicode数据进行显式编码。这就是为什么MyObject().to_string()
有效。您使用的是拉丁-1数据,而不是高ASCII:-)