«

Python3中str、bytes、bytearray转化的方法是什么

时间:2024-4-26 19:55     作者:韩俊     分类: Python


这篇文章主要讲解了“Python3中str、bytes、bytearray转化的方法是什么”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Python3中str、bytes、bytearray转化的方法是什么”吧!

简介

str是采用Unicode编码方式的序列,主要用于显示
bytes是字节序列,主要用于网络和文件传输
bytearray和bytes是一样的,只是它是可变的,它们的关系和str与list类似

str和bytes的相互转化就是编码和解码

str转bytes

使用函数encode

In [2]: s1 = "123abc456ffff"                                                                                                                                                                                                                                                           
In [4]: b = s1.encode("utf-8")                                                                                                                                                  
In [5]: print(b)                                                                                                                                                         
b'123abc456ffff'
In [6]:

bytes转str

使用函数decode

In [6]: s2 = b.decode("utf-8")                                                                                                                                           
In [7]: print(s2)                                                                                                                                                        
123abc456ffff
In [8]:

如果是定义一个bytes:

b = b'123abc456ffff'

bytes和str转化为bytearray

bytes和str转化为bytearray都依赖于bytearray函数

bytes --> bytearray

In [8]: b = b'dafafasfasfsad22136436'
In [10]: s1 = bytearray(b) 
In [11]: print(s1)                                                                                                                                  
bytearray(b'dafafasfasfsad22136436')
In [12]:

str–>bytearray

In [8]: b = 'dafafasfasfsad22136436'
In [10]: s1 = bytearray(b) 
In [11]: print(s1)                                                                                                                                  
bytearray(b'dafafasfasfsad22136436')
In [12]:

hex字符串转为bytearray

In [12]: hexs = "1289"                                                                                                                              
In [13]: br = bytearray.fromhex(hexs)                                                                                                               
In [14]: print(br)                                                                                                                                  
bytearray(b'x12x89')
In [15]:

bytearray转为str和bytes

byarray=bytearray("aabbcc",encoding='utf-8')
str=byarray.decode('utf-8')
bytes=bytes(byarray)
print (byarray)
bytearray(b'aabbcc')
print(str)
aabbcc
print(bytes)
b'aabbcc'

标签: python

热门推荐