【发布时间】:2023-03-22 02:29:01
【问题描述】:
我想转换字符串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)
如果我调用对象station 的get_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' 的文件读取。
【问题讨论】:
-
添加
.encode('iso-8859-1')会得到什么? -
我得到输出:
<object=Station - id=1161, name=Eichst�tt-Landershofen, latitude=48.8779, longitude=11.2347>。是否可以将 � 转换为可读字符? -
@BurhanKhalid:源文件是
iso-8859-1,但我们不知道终端选择了什么编码。希望是'utf-8'。 -
改为添加
.encode('utf-8')是否有效?顺便说一句,当您询问 Unicode 问题时,您应该始终添加 Python 版本标记,因为 Python 3 处理 Unicode 与 Python 2 完全不同。 -
如果我将函数
get_name(self)中的self._name更改为self_name.encode('UTF-8'),我会得到与.encode('iso-8859-1')相同的输出。
标签: python unicode encoding character-encoding python-2.x