python中 如何创建bytes、如何转换str

版权声明:转载请说明地址,谢谢! https://blog.csdn.net/larykaiy/article/details/82950768

Python3版本对文本和二进制数据作了更清晰的区分。文本是Unicode,由str类型表示,二进制数据则由bytes类型表示。Python3不会在任何地方混用str和bytes,这使得两者的区分特别清晰。所以不能拼接字符串和字节包,也无法在字节包里搜索字符串,也不能将字符串传入参数为字节包的函数.同样也不能在字符串中搜索字节包或者字节函数。

  1. 如何由其他类型创建bytes
>>> a = b'abc'
>>> type(a)
<class 'bytes'>
>>> b = bytes('abc','utf-8')
>>> type(b)
<class 'bytes'>
>>> c= bytes([1,2,3,4,5,6,7,8,9])
>>> type(c)
<class 'bytes'>
>>> d = 'abc'.encode(encoding = "utf-8")#encoding也可以不填写
>>> type(d)
<class 'bytes'>
  1. bytes转换成str
>>> str = d.decode()#utf-8默认不填写,其他编码就填写参数decode("gb2312")
>>> type(str)
<class 'str'>

猜你喜欢

转载自blog.csdn.net/larykaiy/article/details/82950768
今日推荐