【问题标题】:Decode an ENCODED unicode string in Python在 Python 中解码一个 ENCODED unicode 字符串
【发布时间】:2013-10-04 02:40:09
【问题描述】:

我需要解码一个“UNICODE”编码的字符串:

>>> id = u'abcdß'
>>> encoded_id = id.encode('utf-8')
>>> encoded_id
'abcd\xc3\x9f'

我遇到的问题是: 使用 Pylons 路由,我将 encoded_id 变量作为 unicode 字符串 u'abcd\xc3\x9f' 而不是常规字符串 'abcd\xc3\x9f'

使用python,我如何解码我的encoded_id变量,它是一个unicode字符串?

>>> encoded_id = u'abcd\xc3\x9f'
>>> encoded_id.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/test/vng/lib64/python2.6/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 4-5: ordinal not in range(128)

【问题讨论】:

  • 如果可能的话,你应该弄清楚为什么你从 Pylons 中获取的字符串被解码为 latin-1(或者它的近亲,windows-1252)而不是 utf-8

标签: python string unicode decode


【解决方案1】:

您有 UTF-8 编码数据(没有 UNICODE 编码数据之类的东西)。

将 unicode 值编码为 Latin-1,然后从 UTF8 解码:

encoded_id.encode('latin1').decode('utf8')

Latin 1 将前 255 个 unicode 点一对一映射到字节。

演示:

>>> encoded_id = u'abcd\xc3\x9f'
>>> encoded_id.encode('latin1').decode('utf8')
u'abcd\xdf'
>>> print encoded_id.encode('latin1').decode('utf8')
abcdß

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-13
    • 2023-04-06
    • 2010-10-14
    • 2018-09-21
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    相关资源
    最近更新 更多