P2转P3时出现‘utf-8‘ codec can‘t decode byte 0xb3 in position 0: invalid start byte(\x、decode解码)
直接上干貨
?
實(shí)例:
abc = b'\x85\xa6\xff\x01\x00\x00\x00\x01!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00root\x00\x14bA(\x15\x0bm\xe8\xdb\x c6*z\xe6\xfa\xfa\x12\xae\xe4=\xca\xc9mysql_native_password\x00'print (abc)結(jié)果:
'utf-8' codec can't decode byte 0xb3 in position 0: invalid start byte
?
將代碼改為:
abc = b'\x85\xa6\xff\x01\x00\x00\x00\x01!\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00root\x00\x14bA(\x15\x0bm\xe8\xdb\x c6*z\xe6\xfa\xfa\x12\xae\xe4=\xca\xc9mysql_native_password\x00'# 多嘗試一下,看哪眾不亂碼 print (abc.decode("utf8","ignore")) 或者 print (abc.decode("utf8")) 或者 print (abc.decode("gbk"))OK
有些字形無(wú)法在編輯器中顯示,或是不想被人看到,可以直接使用二進(jìn)制代碼。
print("\u0394")
#要大寫
print("\U00000394")
#使用名字
print("\N{greek capital letter delta}")
解碼的四個(gè)參數(shù),特別是出現(xiàn)亂碼時(shí)很有必要應(yīng)用這些參數(shù)
#碼的四個(gè)參數(shù)
print((b"\x80abc").decode("utf-8","strict"))#出現(xiàn)錯(cuò)誤
#加上(U+FFFD)
print((b"\x80abc").decode("utf-8","replace"))
#加反斜杠
print((b"\x80abc").decode("utf-8","backslashreplace"))
#直接忽略
print((b"\x80abc").decode("utf-8","ignore"))
運(yùn)行結(jié)果是
字符和二進(jìn)制之間的轉(zhuǎn)換
#將數(shù)值轉(zhuǎn)化為字符
u=chr(40960)+"abce"+chr(1972)
print(u)
u1=chr(123)
print(u1)
#將字符轉(zhuǎn)化為二進(jìn)制
u="中國(guó)abc"
print(u.encode("utf-8"))
#“中國(guó)”是:b'\xe4\xb8\xad\xe5\x9b\xbd'
#print(u.encode("ascii"))
print(u.encode("ascii","ignore"))
print(u.encode("ascii","replace"))
print(u.encode("ascii","xmlcharrefreplace"))
print(u.encode("ascii","backslashreplace"))
print(u.encode("ascii","namereplace"))
最后運(yùn)行結(jié)果如下:
從“namereplace”中獲取每個(gè)字符的名字也很有意思。?
總結(jié)
以上是生活随笔為你收集整理的P2转P3时出现‘utf-8‘ codec can‘t decode byte 0xb3 in position 0: invalid start byte(\x、decode解码)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python 中 assert的使用位置
- 下一篇: Linux中的.bash_ 文件的详细说