• 技术文章 >Python技术 >Python基础教程

    python字节数组如何使用?

    小妮浅浅小妮浅浅2021-07-07 09:59:50原创2915

    1、bytes和bytearray的要素都是在0-255之间的整数,但任何字符串都可以通过字符编码方案存储。字节数组切片或相应的字节数组;字节组可以直接显示ASCII字符。

    s = 'helloèçí'
    b_arr = bytes(s, 'utf_8')
    print(type(b_arr))
    print(type(b_arr))
    for b in b_arr:
      print(b, end=' ')
     
    print()
    print('element of bytes is int number', b_arr[0])
     
    print('splice of bytes is bytes',end = ' ' )
    b_arr_splice = b_arr[:1]
    print(b_arr_splice)
     
    num_b_arr = bytes([299])

    2、struct模块提供了将打包的字节序列转换节序列转换成由不同类型字段组成的元组,也有一些函数用于反向转换,将元组转换成打包的字节序列。该模块可以处理bytes,bytearray和memoryview对象。

    import struct
    record_format = 'hd4s'
    pack_bytes = struct.pack(record_format, 7 , 3.14,b'gbye')
    print(type(pack_bytes))
    print(pack_bytes)
    with open('struct.b', 'wb') as fp:
      fp.write(pack_bytes)
     
    record_size = struct.calcsize(record_format)
    with open('struct.b', 'rb') as fp:
      record_bs = fp.read(record_size)
      print(struct.unpack(record_format, record_bs))

    以上就是python字节数组的使用,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python字节数组
    品易云
    上一篇:python快速排序实现元素递增 下一篇:python文件导入相对路径

    相关文章推荐

    • python数组判断是否存在重复元素• python数组和列表区别是什么• python数组下标怎么获取值并输出• python有哪些编译器• python用circle函数画兔子的方法• python中waitKey如何使用• python traceback如何输出异常• python如何实现自定义异常类• python GIL锁的底层原理探究• python快速排序实现元素递增

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网