UnicodeEncodeError: 'utf-8' 编解码器无法对位置 0-15 中的字符进行编码:不允许代理

kwk*_*892 3 python unicode encoding utf-8 python-3.x

我在尝试打印 unicode 的结果时遇到问题,这是我尝试过的

data = u"\ud835\udc6a\ud835\udc89\ud835\udc90\ud835\udc84\ud835\udc8c"
result = data.encode('utf-8', 'surrogatepass') 
#b'\xed\xa0\xb5\xed\xb1\xaa\xed\xa0\xb5\xed\xb2\x89\xed\xa0\xb5\xed\xb2\x90\xed\xa0\xb5\xed\xb2\x84\xed\xa0\xb5\xed\xb2\x8c'
result.decode('utf-8')
#UnicodeDecodeError: 'utf-8' codec can't decode byte 0xed in position 0: invalid continuation byte

Run Code Online (Sandbox Code Playgroud)

根据 Charbase,\udc90是无效字符 https://charbase.com/dc90-unicode-invalid-character

我可以通过这个网站转换 unicode:https : //www.online-toolz.com/tools/text-unicode-entities-convertor.php在“Decode/Unescape Unicode Entities”部分下

这是结果的屏幕截图

在此处输入图片说明

我怎样才能打印出这个 unicode?我正在从 API 接收数据并希望将其存储在 MySQL 数据库中。目前,MySQL 数据库中的结果是 ???????????

dec*_*eze 5

该网站提供的可能是包含代理对的 JSON 格式转义序列,这实际上是 UTF-16 的东西,Javascript 将字符串视为幕后处理。相同的原始字符串文字在 Python 中无效。您想要的不是让 Python 解释转义序列,而是创建一个包含转义序列的字符串:

>>> r'\ud835\udc6a\ud835\udc89\ud835\udc90\ud835\udc84\ud835\udc8c'
'\\ud835\\udc6a\\ud835\\udc89\\ud835\\udc90\\ud835\\udc84\\ud835\\udc8c'
Run Code Online (Sandbox Code Playgroud)

由于这是 Javascript/JSON 格式,请使用json模块对其进行解码:

>>> import json
>>> json.loads(r'"\ud835\udc6a\ud835\udc89\ud835\udc90\ud835\udc84\ud835\udc8c"')
''
Run Code Online (Sandbox Code Playgroud)

Python 将这个字符串编码为转义序列的方式是:

>>> print(''.encode('unicode-escape').decode('ascii'))
\U0001d46a\U0001d489\U0001d490\U0001d484\U0001d48c
Run Code Online (Sandbox Code Playgroud)