1、bytes、bytearray

  ---Python3 引入的!

  bytes:不可变字节序列,bytearray:字节属组,可变

  都是连续的空间。

2、字符串与bytes

  字符串是字符组成的有序的序列,字符可以使用编码来理解

  bytes 是戒子组成的有序的不可变序列

  bytearray 是戒子组成的有序的可变序列

3、编码、解码

  字符串按照不同的字符集编码encode返回字节序列bytes

    encode(encoding = ‘utf-8', errors = 'strict') ---> bytes    

1 1 In [139]: 'abd'.encode() # 默认是utf-8
2 2 Out[139]: b'abd' # 应该是数字,但是为了让人看,所以显示成这样,所以前面有一个b

  字节序列按照不同的字符集解码decode返回字符串、

    bytes.decode(encoding='utf-8' , errors= 'strict' )   ---> str

    bytearray.decode(encoding= 'utf-8',errors = 'strict') ---> str

1 In [140]: print(b'abd')
2 b'abd'
3 
4 In [141]: _.decode() # _ 表示上次的结果
5 Out[141]: 'abd'

 

    ASCII:American Standard Code for Information

bytes,bytearray

3、bytes定义:

  定义:

    bytes()空bytes

    bytes(int)指定字节的bytes,被0 填充(0是ASCII 0)

In [142]: bytes(5)
Out[142]: b'\x00\x00\x00\x00\x00'

 

    bytes(iterable_of_ints) --> bytes [0-255]的int组成的可迭代对象

    bytes(string, encoding[, errors]) ---> bytes等价于string,encode()

    bytes(bytes_or_buffer) ---> immutable copy of bytes_or_buffer 从一个字节序列或buffer中复制一个新的不可变的bytes对象。

      使用b 前缀定义:

         只允许基本的ASCII使用字符形式b'abc9'

         使用16进制表示b"\x41\x61"  字符串就用 \x41   数字 0x61

bytes,bytearray
 1 In [158]: a = bytes(7) # 定义一个字节长度,用ASCII的十六进制的0填充
 2 
 3 In [160]: a
 4 Out[160]: b'\x00\x00\x00\x00\x00\x00\x00'
 5 
 6 ------------------------------------------------------------------------------
 7 
 8 In [161]: c = bytes(range(10)) # 创建一个字节类型,从0-9
 9 
10 In [162]: c
11 Out[162]: b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t'# python为了让人看懂,所以显示如上所示,如:x09 对ASCII中的 \t, 而其他的对应的字符无法表示,所以以源字节码显示。
12 
13 ------------------------------------------------------------------------------
14 
15 In [163]: d = bytes('efg',encoding='utf-8') #这样用很少,一般都是string.encoding()---默认是utf-8编码
16 
17 In [164]: d
18 Out[164]: b'efg'
19 
20 In [165]: e = bytes(d) 相当于copy了一份
21 
22 In [166]: e
23 Out[166]: b'efg'
bytes,bytearray

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2023-04-02
  • 2022-01-01
  • 2021-06-08
  • 2022-12-23
  • 2021-08-02
猜你喜欢
  • 2021-09-29
  • 2021-11-06
  • 2022-12-23
  • 2022-01-15
  • 2022-12-23
  • 2021-10-14
  • 2022-02-14
相关资源
相似解决方案