【发布时间】:2015-04-17 03:45:06
【问题描述】:
我只是想解码类似 \uXXXX\uXXXX\uXXXX 的字符串。但我得到一个错误:
$ python
Python 2.7.6 (default, Sep 9 2014, 15:04:36)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'\u041e\u043b\u044c\u0433\u0430'.decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/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-4: ordinal not in range(128)
我是 Python 新手。有什么问题?谢谢!
【问题讨论】:
-
为什么要解码已经解码的数据?
-
问题是您使用的是 Python 2,在 Unicode 字符串上有一个欺骗性的
.decode方法。使用python3,问题就会神奇地消失,因为u''.decode会导致AttributeError: 'str' object has no attribute 'decode'。
标签: python python-2.7 utf-8 decode