Python3 字节bytes和字符串str转换

Python3 bytes和str互转

Python 3.6.5

bytes对象初始化

  • 写法一
>>> 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转str

  • 方法一
>>> bytes_obj=b'hello!'
>>> str_obj = str(bytes_obj) # str(bytes_obj,encoding='utf-8')  其他编码加上encoding参数
>>> 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转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()#默认参数encoding='utf-8'
>>> type(bytes_obj)
<class 'bytes'>
>>> bytes_obj
b'\xe4\xbd\xa0\xe5\xa5\xbd\xef\xbc\x81'
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容