python基础之string与bytes的转换
阅读原文时间:2021年04月26日阅读:1

需要转化的原因: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'