P2转P3时出现‘utf-8‘ codec can‘t decode byte 0xb3 in position 0: invalid start byte(\x、decode解码)
直接上干貨
?
實例:
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)結果:
'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
有些字形無法在編輯器中顯示,或是不想被人看到,可以直接使用二進制代碼。
print("\u0394")
#要大寫
print("\U00000394")
#使用名字
print("\N{greek capital letter delta}")
解碼的四個參數,特別是出現亂碼時很有必要應用這些參數
#碼的四個參數
print((b"\x80abc").decode("utf-8","strict"))#出現錯誤
#加上(U+FFFD)
print((b"\x80abc").decode("utf-8","replace"))
#加反斜杠
print((b"\x80abc").decode("utf-8","backslashreplace"))
#直接忽略
print((b"\x80abc").decode("utf-8","ignore"))
運行結果是
字符和二進制之間的轉換
#將數值轉化為字符
u=chr(40960)+"abce"+chr(1972)
print(u)
u1=chr(123)
print(u1)
#將字符轉化為二進制
u="中國abc"
print(u.encode("utf-8"))
#“中國”是: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"))
最后運行結果如下:
從“namereplace”中獲取每個字符的名字也很有意思。?
總結
以上是生活随笔為你收集整理的P2转P3时出现‘utf-8‘ codec can‘t decode byte 0xb3 in position 0: invalid start byte(\x、decode解码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 中 assert的使用位置
- 下一篇: Linux中的.bash_ 文件的详细说