UnicodeEncodeError: 'utf-8' codec can't encode characters in position 0-15: surrogates not allowed
UnicodeEncodeError: 'utf-8' codec can't encode characters in position 0-15: surrogates not allowed
我在尝试打印 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
根据 Charbase,\udc90
是无效字符
https://charbase.com/dc90-unicode-invalid-character
我通过这个网站转换 Unicode:https://www.online-toolz.com/tools/text-unicode-entities-convertor.php 在“Decode/Unescape Unicode 实体”部分下
这是结果的屏幕截图
我怎样才能打印出这个 unicode?我从 API 接收数据并想将其存储在 MySQL 数据库中。当前 MySQL 数据库中的结果是 ????????????
该网站提供的内容很可能是 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'
由于这是 Javascript/JSON 格式,使用 json
模块对其进行解码:
>>> import json
>>> json.loads(r'"\ud835\udc6a\ud835\udc89\ud835\udc90\ud835\udc84\ud835\udc8c"')
''
Python 将此字符串编码为转义序列的方式是:
>>> print(''.encode('unicode-escape').decode('ascii'))
\U0001d46a\U0001d489\U0001d490\U0001d484\U0001d48c
我在尝试打印 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
根据 Charbase,\udc90
是无效字符
https://charbase.com/dc90-unicode-invalid-character
我通过这个网站转换 Unicode:https://www.online-toolz.com/tools/text-unicode-entities-convertor.php 在“Decode/Unescape Unicode 实体”部分下
这是结果的屏幕截图
我怎样才能打印出这个 unicode?我从 API 接收数据并想将其存储在 MySQL 数据库中。当前 MySQL 数据库中的结果是 ????????????
该网站提供的内容很可能是 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'
由于这是 Javascript/JSON 格式,使用 json
模块对其进行解码:
>>> import json
>>> json.loads(r'"\ud835\udc6a\ud835\udc89\ud835\udc90\ud835\udc84\ud835\udc8c"')
''
Python 将此字符串编码为转义序列的方式是:
>>> print(''.encode('unicode-escape').decode('ascii'))
\U0001d46a\U0001d489\U0001d490\U0001d484\U0001d48c