[英]UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 127: unexpected end of data
I have a problem decoding some characters, the error is like this: 我在解码某些字符时遇到问题,错误是这样的:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 127: unexpected end of data
Below is my code, 'response' variable is JSON 下面是我的代码,“ response”变量是JSON
response = requests.post('LINK-TO-API', headers=headers, data=data)
result = ""
for i in response:
result += i.decode('utf-8')
whats wrong with my code? 我的代码有什么问题? Thanks 谢谢
0xD0
( 0b11010000
) is one of many bytes that indicate the start of a multi-byte sequence in UTF-8. 0xD0
( 0b11010000
)是表示多字节序列的UTF-8的开始的字节数中的一个。 The number of 1s before the first 0 indicate the length of the sequence*. 第一个0之前的1表示序列的长度*。 The bits after the first 0 are part of the encoding of the code point. 第一个0之后的位是代码点编码的一部分。
Basically, the iterator of the response has cut a two byte encoding in half. 基本上,响应的迭代器将两个字节的编码减少了一半。 You should read the entire contents of the response before trying to decode it. 您应先读取响应的全部内容,然后再尝试对其进行解码。 eg. 例如。
bytes_ = b''
for chunk in response:
bytes_ += chunk
result = bytes_.decode('utf8')
* bytes starting 10
indicate a continuation byte in a multi-byte sequence rather than a 1-byte encoding. *以10
开头的字节表示多字节序列中的连续字节,而不是1字节编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.