【问题标题】:Why can't I decode \xDF (ß) into UTF-8?为什么我不能将 \xDF (ß) 解码为 UTF-8?
【发布时间】:2018-03-08 14:02:00
【问题描述】:

我有一个字节串b"\xDF"。当我尝试将其解码为 UTF-8 时,会抛出 UnicodeDecodeError。解码为 CP1252 工作正常。在这两个字符集中,0xDF 由字符“ß”表示。那么为什么会出现错误呢?

>>> hex(ord("ß"))
'0xdf'
>>> b"\xDF".decode("utf-8")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xdf in position 0: unexpected end of data
>>> b"\xDF".decode("cp1252")
'ß'

【问题讨论】:

    标签: python-3.x unicode utf-8 cp1252


    【解决方案1】:

    UTF-8 中的所有单字节编码字符都必须在 [0x00 .. 0x7F] (https://en.wikipedia.org/wiki/UTF-8) 范围内。这些相当于 7 位 ASCII。

    对于德语 ß,您将获得 UTF-8 格式的 2 个字节:

    >>> "ß".encode("utf-8")
    

    b'\xc3\x9f'

    解码时也能正常工作:

    b'\xc3\x9f'.decode("utf-8")
    

    'ß'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 2012-12-26
      • 2019-10-24
      相关资源
      最近更新 更多