Python能够编码为UTF-8,但无法解码

2024-06-16 11:28:43 发布

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

下面的代码可以将字符串编码为Utf-8:

#!/usr/bin/python
# -*- coding: utf-8 -*-

str = 'ورود'
print(str.encode('utf-8'))

上面印着:

b'\xd9\x88\xd8\xb1\xd9\x88\xd8\xaf'

但我不能用这个代码解码这个字符串:

#!/usr/bin/python
# -*- coding: utf-8 -*-

str = b'\xd9\x88\xd8\xb1\xd9\x88\xd8\xaf'
print(str.decode('utf-8'))

错误是:

Traceback (most recent call last):
  File "C:\test.py", line 5, in <module>
    print(str.decode('utf-8'))
AttributeError: 'str' object has no attribute 'decode'

请帮帮我。。。

编辑

从答案切换到字节字符串:

#!/usr/bin/python
# -*- coding: utf-8 -*-

str = b'\xd9\x88\xd8\xb1\xd9\x88\xd8\xaf'
print(str.decode('utf-8'))

现在错误是:

Traceback (most recent call last):
  File "C:\test.py", line 5, in <module>
    print(str.decode('utf-8'))
  File "C:\Python34\lib\encodings\cp437.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-3: character maps to <undefined>

Tags: 字符串inbinusrutfencodeprintdecode