Python如何用十六进制字符解码unicode

2024-05-17 15:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我从web爬网脚本中提取了一个字符串,如下所示:

u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91'

我想用utf-8解码u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91'。 使用http://ddecode.com/hexdecoder/,我可以看到结果是'【中字】'

我尝试使用以下语法,但失败了。

msg = u'\xe3\x80\x90\xe4\xb8\xad\xe5\xad\x97\xe3\x80\x91'
result = msg.decode('utf8')

错误:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\encodings\utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-11: ordi
nal not in range(128)

我能问一下如何正确解码这个字符串吗?

谢谢你的帮助。


Tags: 字符串inmsg解码utfdecodexe3xe5