Skip to content

Python bytes

jiaxw32 edited this page Dec 5, 2020 · 1 revision

Python bytes and bytearray

bytes 是不可变对象,支持的数字范围为 0~255 bytearray 是可变对象,支持的数字范围为 0~255

bytes

bytes 文档

>>> print(bytes.__doc__)

bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
  - an iterable yielding integers in range(256)
  - a text string encoded using the specified encoding
  - any object implementing the buffer API.
  - an integer

字节初始化

# convert string to bytes
>>> b'hello'
>>> type(b'hello') # output: <class 'bytes'>

# construct bytes with string
>>> bytes(chr(5), 'ascii')

# construct bytes with list
bytes([5]) # This will work only for range 0-256.

字节转换字符串

b'hello'.decode('utf-8') # output: hello

修改字节数据

bytes 是不可变对象,修改需要重新赋值

>>> s = b'\x01\x02\x03'
>>> s += bytes([5])
>>> s # output: b'\x01\x02\x03\x05'

bytearray

bytearray 文档

>>> print(bytearray.__doc__)
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array

Construct a mutable bytearray object from:
  - an iterable yielding integers in range(256)
  - a text string encoded using the specified encoding
  - a bytes or a buffer object
  - any object implementing the buffer API.
  - an integer

bytearray 初始化

# construct bytesarray with list
>>> listdata = [72, 69, 76, 76, 79]
>>> byteArrayObject = bytearray(listdata)
>>> print(byteArrayObject) # output: bytearray(b'HELLO')

# construct bytearray with string
>>> byteArrObj = bytearray('Python', 'utf-8')

# Initialize bytearray object with number
>>> byteArrObj = bytearray(5)
>>> print(byteArrObj) # output: bytearray(b'\x00\x00\x00\x00\x00')
# Print the size of the bytes object
>>> print(len(byteArrObj)) # output: 5

# Create bytearray and add item using append() method
>>> arrVal = bytearray()
>>> arrVal.append(80)
>>> arrVal.append(121)
>>> print(arrVal) # output: bytearray(b'Py')

bytearray 转 bytes

>>> byteArrObj = bytearray('Python', 'utf-8')
# Convert the bytearray object into a bytes object
>>> byteObject = bytes(byteArrObj)
>>> print(byteObject) # output: b'Python'

bytearray 追加数据

# Initialize bytearray object with string
>>> byte_arr = bytearray('Hello', 'utf-8')
# append data to bytearray with extent method
>>> byte_arr.extend(b' World!')
>>> print(byte_arr) # output: bytearray(b'Hello World!')

# Convert bytearray to string
>>> byte_arr.decode('utf-8') #output: Hello World!

参考资料

Clone this wiki locally