Unicode错误序数不在范围内

rod*_*ing 5 python unicode

我的unicode奇怪的错误.我正在处理unicode很好,但是当我今天早上运行它时,一个项目你''u201d'给了我错误并给了我

UnicodeError: ASCII encoding error: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

我查了代码,显然是它的utf-32但是当我尝试在解释器中解码时:

c = u'\u201d'
c.decode('utf-32', 'replace')
Run Code Online (Sandbox Code Playgroud)

或者它的任何其他操作,它只是没有在任何编解码器中识别它但我发现它是"正确的双引号"

我明白了:

Traceback (most recent call last):
File "<pyshell#154>", line 1, in <module>
    c.decode('utf-32')
  File "C:\Python27\lib\encodings\utf_32.py", line 11, in decode
    return codecs.utf_32_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201d' in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 8

你已经有一个unicode字符串,就没有必要将其解码为unicode字符串再次.

在这种情况下会发生的事情是python有助于首先为您编码,以便您可以从中解码它utf-32.它使用默认编码来执行此操作,恰好是ASCII.这是一个显式编码,向您展示在这种情况下引发的异常:

>>> u'\u201d'.encode('ASCII')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u201d' in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

简而言之,当你有一个unicode文字时u'',就没有必要对它进行解码.

阅读Python Unicode HOWTO中的unicode,编码和默认设置.另一篇关于这个主题的宝贵文章是Joel Spolsky的Minimun Unicode知识帖子.