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?
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.
- source: Initialize byte array /
- encoding: If the source is a string, you must add this parameter to convert, decode the string into bytes.
- 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:
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:
- Bool () function in Python
- Ascii () function in Python
- Bin () function in Python
You should read it
- The ord () function in Python
- Int () function in Python
- The function id () in Python
- Max () function in Python
- Zip () function in Python
- The function dir () in Python
- Bin () function in Python
- The chr () function in Python
- Callable () function in Python
- Sum () function in Python
- The compile () function in Python
- Hex () function in Python