首頁  >  文章  >  後端開發  >  Python內建bytes函數的詳細介紹

Python內建bytes函數的詳細介紹

高洛峰
高洛峰原創
2017-03-21 11:20:331698瀏覽

英文文件:

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

    Return a new “bytes” object, which is an immutable sequence of integers in the range 0 <= x < ; 256. bytes is an immutable version of bytearray – it has the same non-mutating methods and the same indexing and slicing behavior.

Accordingly, constructor arguments are inter#preas for

##Accordingly, constructor arguments are inter#preas for by te#. #說明:

    1. 傳回值為新的不可修改位元組

陣列,每個數字元素都必須在0 - 255範圍內,是bytearray函數的具有相同的行為,差別只是返回的位元組數組不可修改。

    2. 當3個參數都不傳的時候,回傳長度為0的位元組數組

>>> b = bytes()
>>> b
b''
>>> len(b)
0

    3. 當source參數為

字串時,encoding參數也必須提供,函數將字串使用str.encode方法轉換成位元組數組

>>> bytes('中文') #需传入编码格式
Traceback (most recent call last):
  File "", line 1, in 
    bytes('中文')
TypeError: string argument without an encoding
>>> bytes('中文','utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
    4. 當source參數為整數時,傳回這個整數指定長度的空位元組數組

>>> bytes(2)
b'\x00\x00'
>>> bytes(-2) #整数需大于0,用于做数组长度
Traceback (most recent call last):
  File "", line 1, in 
    bytes(-2)
ValueError: negative count
    5. 當source參數為實現了buffer

介面object物件時,那麼將使用唯讀方式將位元組讀取到位元組數組後返回

    6. 當source參數是一個可迭代對象,那麼這個迭代對象的元素都必須符合0 <= x < 256,以便可以初始化到數組裡

>>> bytes([1,2,3])
b'\x01\x02\x03'
>>> bytes([256,2,3])
Traceback (most recent call last):
  File "", line 1, in 
    bytes([256,2,3])
ValueError: bytes must be in range(0, 256)    7. 返回數組不可修改

>>> b = bytes(10)
>>> b
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
>>> b[0]
>>> b[1] = 1 #不可修改
Traceback (most recent call last):
  File "", line 1, in 
    b[1] = 1
TypeError: 'bytes' object does not support item assignment
>>> b = bytearray(10)
>>> b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> b[1] = 1 #可修改
>>> b
bytearray(b'\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00')

以上是Python內建bytes函數的詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn