我有这个清单:
l = [u'\xf9', u'!']
我想在此列表中转换它:
l2 = ['ù','!']
我该怎么办?为什么l.encode()不起作用?
答案 0 :(得分:1)
您使用的是Python 2吗?如果是这种情况,您可能会被Python显示字符串的方式所迷惑。
正如您所注意到的,'\xc3\xb9'
是代码点U + 00F9('ù'
)的UTF-8编码表示。所以:
# code point
>>> u'ù'
u'\xf9'
# seems wrong ?
>>> u'ù'.encode('utf-8')
'\xc3\xb9'
# No, not at all (at least on my UTF-8 terminal)
>>> print(u'ù'.encode('utf-8'))
ù
鉴于你的例子:
>>> l = [u'\xf9', u'!']
>>> print(l)
[u'\xf9', u'!']
>>> l[0]
u'\xf9'
>>> print(l[0])
ù
>>> l2 = [u.encode('utf-8') for u in l]
>>> l2
['\xc3\xb9', '!']
>>> print(l2)
['\xc3\xb9', '!']
>>> print(l2[0])
ù
我同意所有这些都是rather inconsistent and source of frustration。这就是为什么字符串/ unicode支持是Python 3中的一个重要改写。那里:
# Python 3
>>> l = [u'\xf9', u'!']
>>> l
['ù', '!']