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

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

我想转换字符串 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)

如果我调用对象stationget_name() 函数,一切都很好。但是,如果我尝试使用函数 __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)

字符串 u'Eichst\xe4tt-Landershofen' 正在由带有 encoding='ISO-8859-1' 的文件读取。

最佳答案

首先,我建议不要使用 __repr__首先,它并不是真正旨在成为对象的人类可读表示。为此,您应该寻找__str__ , __format__ ,和/或__unicode__

现在,您的问题是 __repr__返回一个 unicode 对象。这是因为当您使用字符串替换 '<name %s>' % _name 时和_name绑定(bind)到 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')

关于python - 在终端上使用 __repr__ 转换显示对象的 unicode 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31722071/

相关文章:

python - Pandas 为每个唯一 ID 选择较高的值

python - Numpy 拆分多维数组

PowerShell 输出文件 : prevent encoding changes

java - 使用 Java 处理 Excel 特殊字符

java - 使用 httpclient 进行 URL 编码

python - 为什么我不能从一个列表理解中得到两个列表?

Python-docx 如何在相同样式的段落后设置空格

python - Unicode编码/解码

python - 如何解码 python 中的非 unicode 字符?

python - 将带有整数和字符串的 unicode 列表编码为 UTF-8/比较两个字符串