use*_*618 0 python unicode encode decode
我的系统: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)
Run Code Online (Sandbox Code Playgroud)
如何从'\ xc4\xe3\xba\xc3'获得"你好"?
这是有效的,因为你要将字节解码为unicode:
'\xc4\xe3\xba\xc3'.decode('gbk')
Run Code Online (Sandbox Code Playgroud)
这不,因为您正在尝试编码字节(已经编码):
'\xc4\xe3\xba\xc3'.encode('gbk')
Run Code Online (Sandbox Code Playgroud)
Python 2中的错误消息在这里没有用,但是你应该只对unicode字符串使用encode:
u'\u4f60\u597d'.encode('gbk') # Gets you back the bytes you had before.
Run Code Online (Sandbox Code Playgroud)
在Python 2中,只需a在交互式提示符处显示转义字符串中的非ascii字符(如\xc3或\u4f60).您可以print a显示字符.或者使用Python 3,它将显示包含unicode字符的字符串.
| 归档时间: |
|
| 查看次数: |
1715 次 |
| 最近记录: |