• python中bytes与bytearray以及encode与decode


    一、encode与decode

    1、bytes主要是给在计算机看的,string主要是给人看的

    2、中间有个桥梁就是编码规则,现在大趋势是utf8

    3、bytes对象是二进制,很容易转换成16进制,例如x64

    4、string就是我们看到的内容,例如'abc'

    5、string经过编码encode,转化成二进制对象,给计算机识别

    6、bytes经过反编码decode,转化成string,让我们看,但是注意反编码的编码规则是有范围,xc8就不是utf8识别的范围

    例如encode使用:

    "哈哈哈".encode("utf-8")    //执行结果为:b'xe5x93x88xe5x93x88xe5x93x88'
    "哈哈哈".encode("gbk")   //执行结果为b'xb9xfexb9xfexb9xfe'

    例如decode使用:

    b'xe5x93x88xe5x93x88xe5x93x88'.decode("utf-8")   //执行结果为:'哈哈哈'
    b'xb9xfexb9xfexb9xfe'.decode("gbk")     //执行结果为:'哈哈哈'
    >>> "哈哈哈".encode("utf-8")
    b'xe5x93x88xe5x93x88xe5x93x88'
    >>> "哈哈哈".encode("gbk")
    b'xb9xfexb9xfexb9xfe'
    >>> b'xe5x93x88xe5x93x88xe5x93x88'.decode("utf-8")
    '哈哈哈'
    >>> b'xb9xfexb9xfexb9xfe'.decode("gbk")
    '哈哈哈'

    二、bytes 与 bytearray

    bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。

    #将数字转换为字节对象
    bytes(1)     //转换后的值为:b'x00'
    #获取12个0填充的byte字节对象
    bytes(12)       //值为:b'x00x00x00x00x00x00x00x00x00x00x00x00'
    #将数字数组转换为字节对象
    bytes([1,2,3])   //值为:b'x01x02x03'
    #将字符串转换为字节对象
    bytes("哈哈哈","utf-8")   //值为:b'xe5x93x88xe5x93x88xe5x93x88'
    #将字符串转换为字节对象
    bytes("哈哈哈","utf-8")  //值为:b'xb9xfexb9xfexb9xfe'
    >>> bytes(1)
    b'x00'
    >>> bytes(12)
    b'x00x00x00x00x00x00x00x00x00x00x00x00'
    >>> bytes([1,2,3])
    b'x01x02x03'
    >>> bytes("哈哈哈","utf-8")
    b'xe5x93x88xe5x93x88xe5x93x88'
    >>> bytes("哈哈哈","gbk")
    b'xb9xfexb9xfexb9xfe'

    bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。

    #将数字转换为字节数组对象
    bytearray(1)     //转换后的值为:bytearray(b'x00')
    #获取12个0填充的byte字节数组对象
    bytearray(12)       //值为:bytearray(b'x00x00x00x00x00x00x00x00x00x00x00x00')
    #将数字数组转换为字节数组对象
    bytearray([1,2,3]   //值为:bytearray(b'x01x02x03')
    #将字符串转换为字节数组对象
    bytearray("哈哈哈","utf-8")   //值为:bytearray(b'xe5x93x88xe5x93x88xe5x93x88')
    #将字符串转换为字节数组对象
    bytearray("哈哈哈","gbk")  //值为:bytearray(b'xb9xfexb9xfexb9xfe')
    >>> bytearray(1)
    bytearray(b'x00')
    >>> bytearray(12)
    bytearray(b'x00x00x00x00x00x00x00x00x00x00x00x00')
    >>> bytearray([1,2,3])
    bytearray(b'x01x02x03')
    >>> bytearray("哈哈哈","utf-8")
    bytearray(b'xe5x93x88xe5x93x88xe5x93x88')
    >>> bytearray("哈哈哈","gbk")
    bytearray(b'xb9xfexb9xfexb9xfe')
  • 相关阅读:
    访问 IIS 元数据库失败
    C# List<T>运用
    Unicode 数据
    讲解SQL Server 2000的Collection排序规则
    delphi Format用法
    delphi 文件的操作
    class of 语句
    深入delphi编程
    delphi 事件委托 未看
    如何让delphi在启动时不自动创建空的工程?
  • 原文地址:https://www.cnblogs.com/liyuanhong/p/12167667.html
Copyright © 2020-2023  润新知