需要轉化的原因:python中字節字符串不能格式化。獲取到的網頁有時候是字節字符串,需要轉化後再解析。
bytes 轉 string 方式一:
>>>b=b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe8\xa6\x81\xe7\x94\xa8python'
>>>string=str(b,'utf-8')
>>>string
"人生苦短,我要用python"
bytes 轉 string 方式二:
>>>b=b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe8\xa6\x81\xe7\x94\xa8python'
>>>string=b.decode()
'人生苦短,我要用python'
string 轉bytes 方式一:
>>> string="人生苦短,我要用python"
>>> b=bytes(string,"utf-8")
>>> b
b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe8\xa6\x81\xe7\x94\xa8python'
string 轉bytes 方式一:
>>> string="人生苦短,我要用python"
>>> b=string.encode()
>>> b
b'\xe4\xba\xba\xe7\x94\x9f\xe8\x8b\xa6\xe7\x9f\xad\xef\xbc\x8c\xe6\x88\x91\xe8\xa6\x81\xe7\x94\xa8python'