python 中 str與bytes的轉換
阿新 • • 發佈:2018-10-25
odin 拋出異常 str1 string 異常 非法字符 ignore bytes nor
# bytes轉字符串方式一 b=b‘\xe9\x80\x86\xe7\x81\xab‘ string=str(b,‘utf-8‘) print(string) # bytes轉字符串方式二 b=b‘\xe9\x80\x86\xe7\x81\xab‘ string=b.decode() # 第一參數默認utf8,第二參數默認strict print(string) # bytes轉字符串方式三 b=b‘\xe9\x80\x86\xe7\x81haha\xab‘ string=b.decode(‘utf-8‘,‘ignore‘) # 忽略非法字符,用strict會拋出異常 print(string) # bytes轉字符串方式四 b=b‘\xe9\x80\x86\xe7\x81haha\xab‘ string=b.decode(‘utf-8‘,‘replace‘) # 用?取代非法字符 print(string) # 字符串轉bytes方式一 str1=‘逆火‘ b=bytes(str1, encoding=‘utf-8‘) print(b) # 字符串轉bytes方式二 b=str1.encode(‘utf-8‘) print(b)
python 中 str與bytes的轉換