UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xcc in position 2: invalid continuation byte

字符串bytesStr内容,类型为Bytes

bytesStr = b'\r\n\xcc\xe1\xca\xbe\xa3\xbaVTY\xd7\xee\xb4\xf3\xd3\xc3\xbb\xa7\xca\xfd\xce\xaa10\xa3\xac\xb5\xb1\xc7\xb0\xd4\xda\xcf\xdfVTY\xd3\xc3\xbb\xa7\xca\xfd\xc4\xbf\xce\xaa1\xa1\xa3\r\n' 

需要将Bytes的字符串转为str的字符串,可读的字符集UTF-8

stringStr = str(bytesStr, encoding='utf-8')

提示:UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xcc in position 2: invalid continuation byte

意思就是“utf-8”字符集没有“0xcc”

换一个字符集GB2312

 stringStr = str(bytesStr, encoding='GB2312')

字符串转换情况:

type of bytes string:<class 'bytes'>
content of byte string:
b'\r\n\xcc\xe1\xca\xbe\xa3\xbaVTY\xd7\xee\xb4\xf3\xd3\xc3\xbb\xa7\xca\xfd\xce\xaa10\xa3\xac\xb5\xb1\xc7\xb0\xd4\xda\xcf\xdfVTY\xd3\xc3\xbb\xa7\xca\xfd\xc4\xbf\xce\xaa1\xa1\xa3\r\n'

type of string Str2:<class 'str'>
change bytes to str, charset GB2312:
 
提示:VTY最大用户数为10,当前在线VTY用户数目为1。

source code:

#!/usr/bin/python3


bytesStr = b'\r\n\xcc\xe1\xca\xbe\xa3\xbaVTY\xd7\xee\xb4\xf3\xd3\xc3\xbb\xa7\xca\xfd\xce\xaa10\xa3\xac\xb5\xb1\xc7\xb0\xd4\xda\xcf\xdfVTY\xd3\xc3\xbb\xa7\xca\xfd\xc4\xbf\xce\xaa1\xa1\xa3\r\n'
print("type of bytes string:"+str(type(bytesStr)))
print("content of byte string:")
print(bytesStr)
print("\n")

#stringStr1 = str(bytesStr, encoding='utf-8')
#print("type of string Str1"+str(type(stringStr1)))
#print(stringStr1)


stringStr2 = str(bytesStr, encoding='GB2312')
print("type of string Str2:"+str(type(stringStr2)))
print("change bytes to str, charset GB2312:")
print(stringStr2)



0 条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注