Python3中str、bytes、bytearray转化
作者:AI学长 时间:2023-01-11 23:29:30
简介
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'\x12\x89')
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'
来源:https://blog.csdn.net/qq_21386397/article/details/106326946
标签:Python3,str,bytes,bytearray,转化
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Django shell调试models输出的SQL语句方法
2022-07-13 00:59:50
对Python中列表和数组的赋值,浅拷贝和深拷贝的实例讲解
2023-06-04 19:17:50
文字解说Golang Goroutine和线程的区别
2023-10-15 18:56:36
TensorFLow 数学运算的示例代码
2023-12-13 21:30:16
![](https://img.aspxhome.com/file/2023/8/113148_0s.png)
轻松掌握执行一个安全的SQL Server安装
2009-01-13 14:03:00
使用IP地址来统计在线人数方法
2007-08-13 12:51:00
Django Rest framework认证组件详细用法
2023-02-20 09:47:08
![](https://img.aspxhome.com/file/2023/8/120958_0s.png)
PHP PDOStatement::fetchAll讲解
2023-06-14 15:54:26
Python 堆叠柱状图绘制方法
2022-05-15 01:39:00
![](https://img.aspxhome.com/file/2023/5/131585_0s.png)
Python中导入模块的几种方式总结
2023-08-04 17:03:54
![](https://img.aspxhome.com/file/2023/2/61432_0s.png)
Python数据类型详解(三)元祖:tuple
2021-05-17 07:49:14
如何使用 Python 读取文件和照片的创建日期
2023-11-17 01:25:00
go语言reflect.Type 和 reflect.Value 应用示例详解
2023-07-18 11:28:43
python判断列表的连续数字范围并分块的方法
2021-01-18 12:04:19
Python Web框架之Django框架文件上传功能详解
2023-06-25 11:19:40
![](https://img.aspxhome.com/file/2023/5/65045_0s.jpg)
ASP中将Excel数据导入到Access
2009-02-02 09:15:00
利用Pytorch实现获取特征图的方法详解
2023-09-11 16:16:02
Python实现个人微信号自动监控告警的示例
2023-02-04 20:03:03
![](https://img.aspxhome.com/file/2023/5/77655_0s.jpg)
Python 面向对象编程的三大特性之继承
2021-08-18 18:19:04
![](https://img.aspxhome.com/file/2023/2/79412_0s.png)
Python编程pydantic触发及访问错误处理
2021-05-19 20:49:07
![](https://img.aspxhome.com/file/2023/4/105604_0s.jpg)