python3 str bytes bytearray 互相转换
在一次aes解密中,我完全弄混了str、bytes、bytearray,结果导致解密的结果不正确。在这里记录一下三者的区别和相互转化的方法。
首先str是采用Unicode编码方式的序列,主要用于显示。
而bytes是字节序列,主要用于网络和文件传输。
bytearray和bytes是一样的,只是它是可变的,它们的关系和str与list类似。
在aes解密或者网络数据中,数据应该是bytes或bytearray。
str和bytes的相互转化就是编码和解码。
str——》bytes
str="aabbcc"
bytes=str.encode('utf-8')print(str)
aabbcc
print(bytes)
b'aabbcc'
更简单的方式是使用b声明是bytes
bytes=b'aabbcc'
bytes——》str
bytes=b"aabbcc"
str=bytes.decode('utf-8')
print(bytes)
b'aabbcc'
print(str)
aabbcc
bytes和str转化为bytearray都依赖于bytearray函数
bytes——》bytearray
bytes=b"aabbcc"
byarray=bytearray(bytes)print(byarray)
bytearray(b'aabbcc')
str——》bytearray
str="aabbcc"
byarray=bytearray(str)print(byarray)
bytearray(b'aabbcc')
常见的网络传输时,有hex字符串转为bytearray的需求可以使用bytearray.fromhex(),这时是不需要编码的。
hexstr="098811"
byarray=bytearray.fromhex(hexstr)
print(byarray)
bytearray(b'\t\x88\x11')
注意到长度减半!!!!!
bytearray——》str bytes
bytearray转为str和bytes 依赖于解码和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'
python3 str bytes bytearray 互相转换相关推荐
- python3 str bytes 字符串 字节 互相转换
1.字符串转成bytes:str.encode('utf-8') 示例1: >>>'abc'.encode('utf-8')>>>b'abc'>>> ...
- python3 的 str bytes 区别
在Python 3版本中,把'xxx'和u'xxx'统一成Unicode编码,即写不写前缀u都是一样的. 在Python 3版本中,所有的字符串都是使用Unicode编码的字符串序列. Python ...
- pythonunicode和str_python2 中 unicode 和 str 之间的转换及与python3 str 的区别
在python2中字符串分为 unicode 和 str 类型 Str To Unicode 使用decode(), 解码 Unicode To Str 使用encode(), 编码 返回数据给前端时 ...
- python3 中bytes与str类型
python3最重要的新特性之一就是对字符串和二进制流做了明确的区分.文本总是unicode,由str类型表示用于显示.二进制则是由bytes类型表示,用于存储和传输.bytes是byte的序列,而s ...
- TypeError: the JSON object must be str, bytes or bytearray, not dict
TypeError: the JSON object must be str, bytes or bytearray, not dict 目录 TypeError: the JSON object m ...
- Python3不用str自带lower转换位小写字母
Python3不用str自带lower转换位小写字母 原题 https://leetcode-cn.com/problems/to-lower-case/ 题目: 不准用字符串自带的lower() A ...
- python str与bytes之间的转换
python str与bytes之间的转换 # bytes object b = b"example"# str object s = "example" # ...
- python str bytes转换
1. 构造str bytes str_var = 'hello world' bytes_var = b'hello world'print(type(str_var)) print(type(byt ...
- python2 和 python3中bytes和str的数据类型以及p32和u32
python3区分bytes 和string这两个数据类型 而python2是没有bytes类型的,是和str混用的 对于同一个地址序列,在python3中用str表示和用bytes,输出的样子会不一 ...
最新文章
- linux的mount(挂载)命令详解
- opencv_python使用cv2.imread()读取中文路径,cv2.imwrite()把图片写入中文路径。
- Windows服务ServicesDependedOn的奇怪问题?
- AndroidStudio自动补完包的快捷键
- Hybris (SAP旗下的软件公司)
- python正则表达式试题_正则表达式练习题2
- 2016年,我的和自己谈谈
- wlan端口服务器无响应,wlan项目遇到的问题,总结
- javascript 编译与执行过程
- Java笔记3:Eclipse添加jar包
- c语言构成循环结构的是,C语言循环结构选择题
- dbv连接mysql_mysql数据库版本控制dbv使用_MySQL
- MAC 用命令查看IP
- 新的服务器装系统前怎么分区吗,新硬盘使用之前要如何分区?硬盘分区常用方法详解...
- WinCC 中批量绑定变量
- 汽车诊断工程师的黎明:并行刷写策略与实现
- 混沌系统matlab程序,dynamos混沌系统的追踪控制matlab代码
- 与或非门——python逻辑电路
- Axure 8.1.0.3377最新激活码
- 钉钉自动打卡并微信通知打卡成功