Home  >  Article  >  Backend Development  >  Detailed explanation of bytearray usage of python function

Detailed explanation of bytearray usage of python function

巴扎黑
巴扎黑Original
2017-08-21 13:44:505087browse

bytearray([source [, encoding [, errors]]])

Chinese description:

bytearray([source [, encoding [, errors]]]) returns a byte array. The Bytearray type is a variable sequence, and the value range of the elements in the sequence is [0,255].

Parameterssource:

If source is an integer, return an initialization array with the length of source;

If source is a string, then follow The specified encoding converts the string into a byte sequence;

If the source is an iterable type, the element must be an integer in [0, 255];

If the source is an interface with the buffer Consistent object, this object can also be used to initialize bytearray.

Version: Newly introduced after python2.6, can also be used in python3!!

English description:

Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the str type has, see String Methods.

The optional source parameter can be used to initialize the array in a few different ways:

If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().

If it is an integer, the array will have that size and will be initialized with null bytes.

If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.

If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.

Without an argument, an array of size 0 is created.

New in version 2.6.

Example demonstration

>>> a = bytearray(3) 
>>> a
bytearray(b&#39;\x00\x00\x00&#39;)
>>> a[0]
 
>>> a[1]
 
>>> a[2]
 
>>> b = bytearray("abc")
>>> b
bytearray(b&#39;abc&#39;)
>>> b[0]
  
>>> b[1]
 
>>> b[2]
 
>>> c = bytearray([1, 2, 3])
>>> c
bytearray(b&#39;\x01\x02\x03&#39;)
>>> c[0]
 
>>> c[1]
 
>>> c[2]
 
>>> d = bytearray(buffer("abc"))
>>> d
bytearray(b&#39;abc&#39;)
>>> d[0]
 
>>> d[1]
 
>>> d[2]

The above is the detailed content of Detailed explanation of bytearray usage of python function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn