在终端上使用__repr__转换显示对象的unicode字符串

时间:2015-07-30 11:04:47

标签: python unicode encoding character-encoding python-2.x

我想转换字符串overflow : auto以在终端上打印对象u'Eichst\xe4tt-Landershofen'

station

如果我调用对象import json class Station(object): def __init__(self,id, name, latitude, longitude): self._id = id self._name = name self._latitude = latitude self._longitude = longitude .... def get_name(self): return self._name def __repr__(self): return '<object=%s - id=%s, name=%s, latitude=%s, longitude=%s>' \ % (self.__class__.__name__, self._id, self._name, self._latitude,\ self._longitude) 的{​​{1}}函数,一切都很好。但是,如果我尝试使用函数get_name()打印整个对象,我会收到以下错误:

station

字符串__repr__正在由print station.Station(id, name, lat, long) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 38: ordinal not in range(128) 的文件读取。

1 个答案:

答案 0 :(得分:3)

首先,我建议首先不要使用__repr__ - 它并不是真正意图成为对象的人类可读表示。为此,您应该关注__str____format__和/或__unicode__

现在,您的问题是__repr__正在返回一个unicode对象。这是因为当您使用字符串替换'<name %s>' % _name并且_name绑定到unicode对象时,python 2会自动将字节串模板“提升”为unicode以实现替换。

现在,当看到从repr返回的unicode对象时,python将尝试通过使用sys.getdefaultencoding()对其进行编码来获取字节对象,这显然是'ascii',并且因为无法对站进行编码而失败使用ascii字符集。

如果您绝对需要repr中的非ascii字符(为什么??),则必须选择终端可以理解的编码,并对该字符集进行编码。以下是utf-8的示例,它可能适用于您的系统:

import json

class Station(object):
    def __init__(self,id, name, latitude, longitude):
        self._id = id
        self._name = name
        self._latitude = latitude
        self._longitude = longitude

    def get_name(self):
        return self._name

    def __unicode__(self):
        return u'<object={} - id={}, name={}, latitude={}, longitude={}>'.format(
            self.__class__.__name__, 
            self._id, 
            self.get_name(), 
            self._latitude,
            self._longitude,
        )

    def __repr__(self):
        return unicode(self).encode('utf8')