English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The bytes() method returns an immutable byte object, which is initialized with the given size and data.
The syntax of the bytes() method is:
bytes([source[, encoding[, errors]]])
The bytes() method returns a bytes object, which is an immutable (cannot be modified) sequence of integers, ranging from 0 <= x <256.
If you want to use the variable version, please usebytearray()method.
bytes() has three optional parameters:
source (optional) -The array used to initialize bytes from the source.
encoding (optional) -The encoding of the string if source is a string.
errors (optional) -The action taken when the encoding conversion fails if source is a string (more information:String encoding)
The source parameter can be used to initialize the byte array as follows:
Type | Description |
---|---|
String | To convert a string to bytes using str.encode(), you must also provideencoding and optionalError |
Integer | Create an array that provides size, and all arrays are initialized to null |
Object | The read-only buffer of the object will be used to initialize the byte array |
Iterable | Create an array of size equal to the count of the iterable, and initialize it with the elements of the iterable. It must be 0 <= x <256The integer between them is iterable |
No source (arguments) | Create an array of size 0 |
The bytes() method returns a bytes object with the given size and initial value.
string = "Python is interesting." # Encoding as “utf-8”string arr = bytes(string, 'utf-8) print(arr)
When running the program, the output is:
b'Python is interesting.'
size = 5 arr = bytes(size) print(arr)
When running the program, the output is:
b'\x00\x00\x00\x00\x00'
rList = [1, 2, 3, 4, 5] arr = bytes(rList) print(arr)
When running the program, the output is:
b'\x01\x02\x03\x04\x05'