python字節串的構造函數 bytes


字節串的構造函數 bytes

  bytes() 生成一個空的字節串等同於b''
  bytes(整數可迭代對象) 用可迭代對象初始化了個字符串
  bytes(整數n) 生成n個值為0的字節串
  bytes(字符串,encoding='utf-8') 用字符串的轉換編碼生成一個字節串

  示例:
  b = bytes() # b綁定 b''
  b = bytes([65, 66, 67, 68]) # b=b'ABCD'
  b = bytes(5) # b='\x00\x00\x00\x00\x00'
View Code

  bytes 的運算
    + += * *=
    < <= > >= == !=
    in / not in
    索引和切片
    注: 運算規則同字符串的運算規則

  示例:
  b = b'ABCD'
  b'BC' in b # True
  66 in b # True
  print(b[0]) # 65
  print(b[-1]) # 68
View Code

  能用於字節串的內建函數
    len(x)
    max(x)
    min(x)
    sum(x)
    any(x)
    all(x)

  bytes 和 str 的區別
    bytes 用來存儲字節(0~255的整數)
    str 用來存儲unicode字符(0~0x10FFFF的整數)

  bytes 與 str 的轉換
    編碼(encode)
      str -------------> bytes
      b = s.encode(encoding='utf-8')

    解碼(decode)
      bytes -----------> str
      s = b.decode(encoding='utf-8')

    示例:
      s = 'ABC中文'
      b = s.encode() # 等同於 b = s.encode('utf-8')
      s2 = b.decode() # 將字節串解碼為字符串
View Code

字節數組 bytearray
  可變的字節序列

  構造函數 bytearray
    bytearray() 創建空的字節數組
    bytearray(整數n) 生成n個值為0的字節數組
    bytearray(整型可迭代對象) 用可迭代對象初始化一個字節數組
    bytearray(字符串,encoding='utf-8') 用字符串的轉換編碼生成一個字節數組

  運算:
    + += * *=
    < <= > >= == !=
    in / not in 運算符
    索引 index / 切片 slice
    (字節數組的索引和切片可以賦值操作,規則同列表的索引和切片的賦值規則)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM