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'
本文详细介绍了Python3中bytes类型与str类型之间的转换方法。包括bytes对象的两种初始化方式,bytes转str的两种方法,以及str转bytes的两种写法。适合Python初学者理解和掌握字符串与字节串的基本操作。

3万+

被折叠的 条评论
为什么被折叠?



