【问题标题】:Unicode and string with encodingUnicode 和带编码的字符串
【发布时间】:2014-03-18 12:13:41
【问题描述】:

为什么会这样:

a = 'a'.encode('utf-8')
print unicode(a)
>>> u'a'

这会给我一个错误:

b = 'b'.encode('utf-8_sig')
print unicode(b)

说:
>>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)

【问题讨论】:

    标签: string unicode encoding utf-8 python-2.5


    【解决方案1】:

    因为你还没有告诉unicode使用什么编码:

    >>> a = 'a'.encode('utf-8')
    >>> print unicode(a)
    a
    >>> b = 'b'.encode('utf-8_sig')
    >>> print unicode(b)
    
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        print unicode(b)
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
    >>> print unicode(b, 'utf-8_sig')
    b
    

    【讨论】:

    • 是 unicode 使用 'utf-8' bei 默认还是为什么我在第一个问题中没有收到错误?
    • 'a'.encode('utf-8') 只是'a',所以你不需要告诉unicode 如何处理它,而'b'.encode('utf-8_sig')'\xef\xbb\xbfb'
    【解决方案2】:

    'ascii' codec can't decode byte 0xef 说了两件事:

    1. unicode(b) 使用 ascii (sys.getdefaultencoding()) 字符编码
    2. \xef 字节不在 ascii 范围内。它是'utf-8-sig'编码引入的BOM中的第一个字节(在Windows上使用)

    第一个示例有效,因为 'a' 字节串是 ascii。 'a'.encode('utf-8') 等价于'a'.decode(sys.getdefaultencoding()).encode('utf-8'),在这种情况下它等于'a' 本身。

    一般情况下,使用bytestring.decode(character_encoding) = unicode_stringunicode_string.encode(character_encoding) = bytestring。 bytestring 是一个字节序列。 Unicode 字符串是一系列 Unicode 代码点。

    不要在字节串上调用.encode()'a' 是 Python 2 中的字节串文字。u'a' 是 Unicode 文字。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多