UnicodeEncodeError:'ascii'编解码器不能编码位置0-5的字符:序数不在范围内(128)

Ser*_*hyk 12 python decode utf-8 python-2.7

我只是想解码\ 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)
Run Code Online (Sandbox Code Playgroud)

我是Python新手.有什么问题?谢谢!

Mar*_*ers 21

Python正试图提供帮助.您无法解码 Unicode数据,它已经被解码.所以Python首先会对数据进行编码(使用ASCII编解码器)来获取要解码的字节.这种隐式编码失败了.

如果你有Unicode数据,只有编码为UTF-8 才有意义,而不是解码:

>>> print u'\u041e\u043b\u044c\u0433\u0430'
?????
>>> u'\u041e\u043b\u044c\u0433\u0430'.encode('utf8')
'\xd0\x9e\xd0\xbb\xd1\x8c\xd0\xb3\xd0\xb0'
Run Code Online (Sandbox Code Playgroud)

如果你想要一个Unicode值,那么u'...'你需要使用Unicode文字().无需进一步解码.

相反的隐式转换发生在另一个方向; 如果你试图编码一个bytestring,你会触发一个隐式解码:

>>> u'\u041e\u043b\u044c\u0433\u0430'.encode('utf8').encode('utf8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)


Ran*_*han 13

你可以设置默认编码utf-8.

import sys  
reload(sys)  
sys.setdefaultencoding('utf-8')
Run Code Online (Sandbox Code Playgroud)

  • 馊主意.对于不了解编码的人来说,这是一个令人讨厌的讨厌的黑客攻击:https://anonbadger.wordpress.com/2015/06/16/why-sys-setdefaultencoding-will-break-code/ (5认同)
  • 请**不要**使用此[货物崇拜](https://en.wikipedia.org/wiki/Cargo_cult_programming)解决方案.由于某种原因,从模块中删除了`sys.setdefaultencoding`,更改Python 2的隐式默认编码可能会破坏依赖于正常行为的第三方库. (3认同)