bytes() returns an immutable bytes object, made up of a sequence of integers in the range 0 <=x < 256.
The returned bytes sequence is immutable. A mutable bytes sequence can be used instead by calling is bytearry() .
Syntax
bytes(]])
bytes()
takes three optional parameters:
- source – initialize the array of bytes. Can be String or Integer
- encoding – if the source is a string, the encoding of the string
- errors – the action to take when the encoding conversion fails
Example
Creating empty array of bytes
x = bytes(3)
print(x)
Output
b'\x00\x00\x00'
Introducing a String
str = "CodeIt"
# encoding 'utf-8'
ex1= bytes(str, 'utf-8')
#encdoing 'utf-16'
ex2= bytes(str, 'utf-16')
print(ex1)
print(ex2)
Output
b'CodeIt'
b'\xff\xfeC\x00o\x00d\x00e\x00I\x00t\x00'