/  Bytearray() method in Python Built in Function

Bytearray() method in Python Built in Function

 

bytearray method in built function returns the arrays of the bytes given in the function.this method is a mutable sequence of integers in the range 0 <=x<256.

 

Syntax:

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

 

Parameters:

Bytes method has 3 parameters. These parameters are optional

  • Source: this is used to initialize the source of an array
  • Encoding: if the source is a string then this is used as encoding of the string
  • Errors: if the source is string, this parameter takes the action when the encoding conversion fails.

 

Table for different source parameters

Type of sourceDescription
StringThis converts the string into bytes by using str.encode(). We have to provide encode and errors
IntegerThis creates an array of provided size
ObjectTo initialize the byte array read only buffer object is used
IterableIt creates an array whose size is equal to the Iterable count
No source(arguments)It creates an array with size 0

 

           

Example-1:

 

Converting string into array of bytes

x = "Rainbow has 7 colors"
text= bytes( x ,'utf-8')
print(text)

 

Output:

Bytearray() method in PythonBuilt in Function

 

Example-2:

 

Integer size of array of bites

x = bytes (7)
print(x)

 

Output:

Bytearray() method in PythonBuilt in Function

 

Example-3:

 

Iterable list for array of bytes

text = [9,5,6,7,8]
x= bytes( text)
print(x)

 

Output: