这是一个常见的问题,因此这里有一个相对详细的说明。
对于非Unicode字符串(即没有u
前缀的字符串,例如u'\xc4pple'
),必须从本地编码(iso8859-1
/latin1
,除非 使用神秘的sys.setdefaultencoding
函数进行修改)解码为unicode
,然后编码到可以显示所需字符的字符集,本例中我建议使用UTF-8
。
首先,这是一个方便的实用函数,它将帮助阐明Python 2.7字符串和unicode的模式:
>>> def tell_me_about(s): return (type(s), s)
一个普通字符串
>>> v = "\xC4pple"
>>> tell_me_about(v)
(<type 'str'>, '\xc4pple')
>>> v
'\xc4pple'
>>> print v
?pple
解码iso8859-1字符串 - 将普通字符串转换为Unicode
>>> uv = v.decode("iso-8859-1")
>>> uv
u'\xc4pple'
>>> tell_me_about(uv)
(<type 'unicode'>, u'\xc4pple')
>>> print v.decode("iso-8859-1")
Äpple
>>> v.decode('iso-8859-1') == u'\xc4pple'
True
更多举例说明——使用“Ä”
>>> u"Ä" == u"\xc4"
True
>>> "Ä" == u"\xc4"
False
>>> "Ä".decode('utf8') == u"\xc4"
True
>>> "Ä" == "\xc4"
False
将编码转换为UTF
>>> u8 = v.decode("iso-8859-1").encode("utf-8")
>>> u8
'\xc3\x84pple'
>>> tell_me_about(u8)
(<type 'str'>, '\xc3\x84pple')
>>> u16 = v.decode('iso-8859-1').encode('utf-16')
>>> tell_me_about(u16)
(<type 'str'>, '\xff\xfe\xc4\x00p\x00p\x00l\x00e\x00')
>>> tell_me_about(u8.decode('utf8'))
(<type 'unicode'>, u'\xc4pple')
>>> tell_me_about(u16.decode('utf16'))
(<type 'unicode'>, u'\xc4pple')
Unicode、UTF 和 Latin1 之间的关系
>>> print u8
Äpple
>>> print u8.decode('utf-8')
Äpple
>>> print u16
���pple
>>> print u16.decode('utf16')
Äpple
>>> v == u8
False
>>> v.decode('iso8859-1') == u8
False
>>> u8.decode('utf-8') == v.decode('latin1') == u16.decode('utf-16')
True
Unicode 异常
>>> u8.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
>>> u16.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)
>>> v.encode('iso8859-1')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0:
ordinal not in range(128)
您可以通过将具体编码(latin-1、utf8、utf16)转换为unicode来解决这些问题,例如:u8.decode('utf8').encode('latin1')
。
因此,以下是一些原则和概括:
str
类型是一组字节,可以采用多种编码方式,如Latin-1、UTF-8和UTF-16。
unicode
类型是一组字节,可转换为任意数量的编码方式,最常见的是UTF-8和Latin-1(ISO8859-1)。
print
命令 有自己的编码逻辑,设置为sys.stdout.encoding
,默认为UTF-8。
- 必须先将
str
解码为unicode,然后再转换为另一种编码方式。
当然,在Python 3.x中所有这些都会改变。
希望这能够帮助到您。
进一步阅读
以及Armin Ronacher的非常生动的抨击: