gpt4 book ai didi

python3 unicode-escape 不适用于非 ascii 字节?

转载 作者:太空狗 更新时间:2023-10-29 18:07:51 27 4
gpt4 key购买 nike

<分区>

在python2中,有string-escapeunicode-escape。对于 utf-8 字节字符串,string-escape 可以转义\并保留非 ascii 字节,例如:

"你好\\n".decode('string-escape')
'\xe4\xbd\xa0\xe5\xa5\xbd\n'

但是,在python3中,string-escape被移除了。我们必须将字符串编码为字节并使用 unicode-escape 对其进行解码:

"This\\n".encode('utf_8').decode('unicode_escape')
'This\n'

它确实适用于 ascii 字节。但非 ascii 字节也会被转义:

"你好\\n".encode('utf_8')
b'\xe4\xbd\xa0\xe5\xa5\xbd\\n'
"你好\\n".encode('utf_8').decode('unicode_escape').encode('utf_8')
b'\xc3\xa4\xc2\xbd\xc2\xa0\xc3\xa5\xc2\xa5\xc2\xbd\n'

所有非ascii字节都被转义,导致编码错误。

那么有解决办法吗?在 python3 中是否可以保留所有非 ascii 字节并解码所有转义字符?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com