Python bytes() Method
The bytes()
method returns an immutable object of the bytes class initialized with integers' sequence in the range of 0 to 256.
Syntax:
bytes(source, encoding, errors)
Parameters:
- source: (Optional) An integer or iterable to convert it to a byte array.
- If the source is a string, it must be with the encoding parameter.
- If the source is an integer, the array will have that size and will be initialized with null bytes.
- If the source is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
- If the source is the iterable object, it must have integer elements in the range 0 to 256.
- encoding: (Optional) The encoding of the string if the source is a string.
- errors: (Optional) The action to take if the encoding conversion fails.
Return Value:
Returns a byte object.
The following example converts the given integer to byte.
print(bytes(1))
print(bytes(2))
print(bytes(3))
b'\x00'
b'\x00\x00'
b'\x00\x00\x00'
If the source
arguement is a string, and no encoding method is specified, a TypeError
exception is returned.
print(bytes('Hello'))
TypeError: string argument without an encoding
The encoding method needs to be specified to get a bytes object from the string, as shown below.
print(bytes('Hello World','utf-8'))
b'Hello World'
An iterable can also be converted to a bytes object as follows.
nums = [1, 2, 3, 4, 5]
print(bytes(nums))
b'\x01\x02\x03\x04\x05'