将 string.decode('utf8') 从 python2 转换为 python3



我正在将一些代码从python2转换为python3。

在python2中,我可以做以下事情:

>>> c = 'xe5xb8x90xe6x88xb7'
>>> print c
帐户
>>> c.decode('utf8')
u'u5e10u6237'

如何在 python3 中获得相同的输出 (u'\u5e10\u6237')?


编辑

对于其他有此问题的人,在查看了响应后,我意识到要利用结果,需要将每个字符视为单个元素。转义的 unicode 表示形式(如 '\u5e10\u6237' )是一个字符串,因此它不会自然地分成与原始中文字符对应的部分。

>>> c = '帐户'
>>> type(c.encode('unicode-escape').decode('ascii'))
<class 'str'>
>>> [l for l in c.encode('unicode-escape').decode('ascii')]
['\', 'u', '5', 'e', '1', '0', '\', 'u', '6', '2', '3', '7']

您必须分隔输入字符串中的每个字符并将其单独转换为数组,除非您想在程序的下一部分再次解析它。因此,我的解决方案是:

>>> [l.encode('unicode-escape').decode('ascii') for l in c]
['\u5e10', '\u6237']

另一种解决方案使每个字符都变成十六进制表示形式:

>>> [hex(ord(l)) for l in c]
['0x5e10', '0x6237']

感谢您的帮助。

称为"unicode-escape"编码。下面是如何在 python3 中实现此行为的示例:

In [11]: c = b'xe5xb8x90xe6x88xb7'
In [12]: d = c.decode('utf8')
In [13]: print(d)
帐户
In [14]: print(d.encode('unicode-escape').decode('ascii'))
u5e10u6237

如果您希望它bytes而不是str,您可以简单地摆脱.decode('ascii')

返回与

python2 中相同的 unicode 是不可能的:我还没有看到像 python2 和 python3 中那样的 unicode 对象。但是可以获取 unicode 对象的值。

为此,您需要做几件事:
- 创建值为"\xe5\xb8\x90\xe6\x88\xb7"的字节元素 - 将此字节元素转换为字符串 - 从字符串中获取 unicode 代码

第一步非常简单。要创建与 c 具有相同值的字节元素 'c',只需执行以下操作:

c = b'xe5xb8x90xe6x88xb7'

然后,读取元素

c_string = c.decode() # default encoding is utf-8

最后,我创建了一个函数来将字符串转换为其字符 + unicode 表示形式

def get_unicode_code(text):
    result = ""
    for char in text:
        ord_value = ord(char)
        if ord_value < 128:
            result += char
        else:
            hex_string = format(ord_value, "x") # turning the int into its hex value
            if len(hex_string) == 2:
                unicode_code = "\x"+hex_string
            elif len(hex_string) == 3:
                unicode_code = "\u0"+hex_string
            else:
                unicode_code = "\u"+hex_string
            result += unicode_code
    return result

get_unicode_code(d)将返回与d.encode('unicode-escape').decode('ascii')相同的结果,尽管它很可能效率较低。

它将字符串作为参数,并返回一个带有 unicode 的字符串,而不是它所表示的字符。

最新更新