Bytearray () function in Python

Bytearray () function in Python returns the bytearray object of a given byte array. How is the syntax of bytearray () function, what parameters does it have and how to use it?

Bytearray () function in Python returns the bytearray object of a given byte array. How is the syntax of bytearray () function, what parameters does it have and how to use it?

Syntax of bytearray () function:

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

The bytearray () function returns a bytearray object which is a variable string (can be modified) of integers in the range 0 <= x <256.

If you want the immutable version use the byte () method.

Parameters of bytearray () function:

Bytearray () function has 3 parameters, all 3 are optional, yes or no.

  1. source: Initialize byte array /
  2. encoding: If the source is a string, you must add this parameter to convert, decode the string into bytes.
  3. errors: If the source is a string, errors will provide action to retrieve when the decoding process fails.

The source parameter can be used to initialize the byte array in the following ways:

Type DescriptionString Convert string to byte using str.encode (), and must provide both encoding and errors then the Integer option Creates an array with the provided size, all initialized to null. Object Read-only buffer of the object to be used to initialize byte arrays Iterable Create an array of size equivalent to the iterable count and initialize iterable elements. Integers must be between 0 <= x

What value does the function bytearray () return?

The bytearray () function returns a byte array with a given size and initial values.

Example of bytearray () function:

 # Ví dụ 1: source là chuỗi 
string1 = "quantrimang.com."


# encoding là 'utf-8'
mang1 = bytearray(string1, 'utf-8')
print(mang1)

# Ví dụ 2: source là số


string2 = 10

mang2 = bytearray(string2)
print(mang2)

#Ví dụ 3: source là list


ListSo = [2,4,6,8,10]


mang3 = bytearray(ListSo)
print(mang3)

When running the above program, we get the following output:

 bytearray(b'quantrimang.com.') 
bytearray(b'x00x00x00x00x00x00x00x00x00x00')
bytearray(b'x02x04x06x08n')

See more:

  1. Bool () function in Python
  2. Ascii () function in Python
  3. Bin () function in Python
Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile