Python3 bytes和str互轉(zhuǎn)
Python 3.6.5
bytes對(duì)象初始化
- 寫法一
>>> bytes_obj = bytes('HELLO!',encoding='utf-8')
>>> type(bytes_obj)
<class 'bytes'>
>>> bytes_obj
b'HELLO\xef\xbc\x81'
- 寫法二
>>> bytes_obj=b'hello!'
>>> type(bytes_obj)
<class 'bytes'>
>>> bytes_obj
b'hello!'
bytes轉(zhuǎn)str
- 方法一
>>> bytes_obj=b'hello!'
>>> str_obj = str(bytes_obj) # str(bytes_obj,encoding='utf-8') 其他編碼加上encoding參數(shù)
>>> type(str_obj)
<class 'str'>
>>> str_obj
"b'hello!'"
- 寫法二
>>> bytes_obj=b'hello!'
>>> str_obj = bytes.decode(bytes_obj) # bytes.decode(bytes_obj,encoding='utf-8'),其他編碼加上encoding
>>> type(str_obj)
<class 'str'>
>>> str_obj
'hello!'
str轉(zhuǎn)bytes
- 寫法一
>>> str_obj='你好!'
>>> bytes_obj = str.encode(str_obj) #str.encode(str_obj,encoding='utf-8')
>>> type(bytes_obj)
<class 'bytes'>
>>> bytes_obj
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x81'
- 寫法二
>>> str_obj='你好!'
>>> bytes_obj = str_obj.encode()#默認(rèn)參數(shù)encoding='utf-8'
>>> type(bytes_obj)
<class 'bytes'>
>>> bytes_obj
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x81'