如何将unicode编码为字节,以便可以检索到原始字符串?在Python 3.11

问题描述 投票:0回答:1

在 python 3.11 中,我们可以对字符串进行编码,如下所示:

string.encode('ascii', '反斜杠替换')

这非常适用于:

hellö
=>
hell\\xf6

但是当我插入

hellö w\\xf6rld
时我得到
hell\\xf6 w\\xf6rld
(注意第二个有一个看起来像字符转义序列的文字部分)

或者换句话说,以下内容成立:

'hellö wörld'.encode('ascii', 'backslashreplace') == 'hellö w\\xf6rld'.encode('ascii', 'backslashreplace')

这显然意味着数据已因编码而丢失。

有没有办法让python真正正确编码?那么反斜杠本身也被转义了吗?或者图书馆可以这样做吗?

python character-encoding
1个回答
0
投票

使用不带错误处理程序的

unicode_escape
编解码器,而不是带错误处理程序的
ascii
编解码器。 您收到数据非 ASCII 错误,并且错误处理程序导致丢失。 结果将仅为 ASCII 字符,但它将处理反斜杠:

>>> 'hellö wörld'.encode('unicode_escape') == 'hell\\xf6 w\\xf6rld'.encode('unicode_escape')
False
>>> 'hellö wörld'.encode('unicode_escape')
b'hell\\xf6 w\\xf6rld'
>>> 'hell\\xf6 w\\xf6rld'.encode('unicode_escape')
b'hell\\\\xf6 w\\\\xf6rld'
© www.soinside.com 2019 - 2024. All rights reserved.