如何获得我的角色?
我的系统: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' 得到“你好”?
my system:xp+python27
the codec,
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)
How can I get "你好" from '\xc4\xe3\xba\xc3' ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是可行的,因为您正在将字节解码为 unicode:
这不行,因为您正在尝试对字节进行编码(已经编码):
Python 2 中的错误消息在这里没有帮助,但您应该只在 unicode 上使用编码strings:
在 Python 2 中,只需在交互式提示符处执行
a
就会显示转义字符串中的非 ascii 字符(例如\xc3
或\u4f60
)。您可以执行print a
来显示字符。或者使用 Python 3,它将显示包含 unicode 字符的字符串。This works, because you're decoding bytes to unicode:
This doesn't, because you're trying to encode bytes (which are already encoded):
The error message in Python 2 is unhelpful here, but you should only use encode on unicode strings:
In Python 2, just doing
a
at the interactive prompt will show non-ascii characters in strings escaped (like\xc3
or\u4f60
). You can doprint a
to display the characters. Or use Python 3, which will display strings including the unicode characters.您的 Python shell 无法打印
gbk
编码的字符串。它就在那里,只是你无法打印它。Your Python shell can't print the
gbk
encoded string. It is there, you just can't print it.他的意思是,在编码和打印时,它不会根据需要显示
但如果指定:
您应该使用:
he means that when encoding and printing it is not displaying as needed
But if specifying:
You should use: