Python3 bytes 函數

Python3 內置函數 Python3 內置函數


描述

bytes 函數返回一個新的 bytes 對象,該對象是一個 0 <= x < 256 區間內的整數不可變序列。它是 bytearray 的不可變版本。

語法

以下是 bytes 的語法:

class bytes([source[, encoding[, errors]]])

參數

  • 如果 source 為整數,則返回一個長度為 source 的初始化數組;
  • 如果 source 為字串,則按照指定的 encoding 將字串轉換為位元組序列;
  • 如果 source 為可迭代類型,則元素必須為[0 ,255] 中的整數;
  • 如果 source 為與 buffer 介面一致的對象,則此對象也可以被用於初始化 bytearray。
  • 如果沒有輸入任何參數,默認就是初始化數組為0個元素。

返回值

返回一個新的 bytes 對象。


實例

以下展示了使用 bytes 的實例:

實例

>>>a = bytes([1,2,3,4]) >>> a b'\x01\x02\x03\x04' >>> type(a) <class 'bytes'> >>> >>> a = bytes('hello','ascii') >>> >>> a b'hello' >>> type(a) <class 'bytes'> >>>

Python3 內置函數 Python3 內置函數