我的系统:xp + python27 编解码器, xp gbk; python 27 ascii
>>> a = '你好'
>>> a
'\xc4\xe3\xba\xc3'
>>> print a
你好
>>> '\xc4\xe3\xba\xc3'.decode('gbk')
u'\u4f60\u597d'
>>> '\xc4\xe3\xba\xc3'.encode('gbk')
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)
如何从'\ xc4 \ xe3 \ xba \ xc3'获得“你好”?
答案 0 :(得分:6)
这很有效,因为你要将字节解码为unicode:
'\xc4\xe3\xba\xc3'.decode('gbk')
这不是,因为你正在尝试编码字节(已经编码):
'\xc4\xe3\xba\xc3'.encode('gbk')
Python 2中的错误消息在这里没有用,但你应该只对unicode字符串使用encode:
u'\u4f60\u597d'.encode('gbk') # Gets you back the bytes you had before.
在Python 2中,只需在交互式提示符下执行a
即可在转义的字符串中显示非ascii字符(如\xc3
或\u4f60
)。您可以print a
显示字符。或者使用Python 3,它将显示包含unicode字符的字符串。
答案 1 :(得分:0)
您的Python shell无法打印gbk
编码的字符串。就在那里,你无法打印它。
答案 2 :(得分:0)
他的意思是,在编码和打印时,它没有按需显示
>>> a = u'\u4f60\u597d'.encode('gbk')
>>> print a
���
>>> a
'\xc4\xe3\xba\xc3'
但如果指定:
>>> a = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print a
你好
您应该使用:
>>> c = '\xe4\xbd\xa0\xe5\xa5\xbd'.decode('gbk')
>>> c
u'\u6d63\u72b2\u30bd'
>>> c = c.encode('gbk')
>>> print c
你好